Leetcode_859_BuddyStrings_Easy
目录
Leetcode_859_BuddyStrings_Easy
1、Leetcode_859_BuddyStrings_Easy
1、Leetcode_859_BuddyStrings_Easy
(1)、题目描述
* 难度:Easy
* 类别Tag:String
* 问题描述:
* Given two strings A and B of lowercase letters, return true
* if and only if we can swap two letters in A so that the result equals B.
* <p>
* Example 1:
* Input: A = "ab", B = "ba" Output: true
* Example 2:
* Input: A = "ab", B = "ab" Output: false
* Example 3:
* Input: A = "aa", B = "aa" Output: true
* Example 4:
* Input: A = "aaaaaaabc", B = "aaaaaaacb" Output: true
* Example 5:
* Input: A = "", B = "aa" Output: false
* Note:
* 0 <= A.length <= 20000
* 0 <= B.length <= 20000
* A and B consist only of lowercase letters.
(2)、思路分析:
* A和B的长度必须相同,否则返回false;
* 寻找A和B不同字符个数,当出现多于2个时,返回false;
* 对于出现一对字符不同的,返回false;
* 没有出现不同字符的情况,要求字符串中必须含有相同字符,否则返回false;
* 出现两对不同字符,需要对应位置的两个元素两两相等才可以。
* 注意:由于必须要交换一次,所以ab和ab这种相同的字符串,返回false;
* 而abb和abb就返回true,因为含有相同字符。
* 在遍历过程中,利用统计数组统计字符出现次数,若某个字符出现2次以上,利用isRepeat标志是否含有相同字符。
*/
(3)、Java代码
public boolean buddyStrings(String A, String B) {
if (A == null && B == null) return true;
if (A.length() != B.length()) return false;
char[] charsA = A.toCharArray(), charsB = B.toCharArray();
int count = 0;
int[] indexs = new int[2];//保存两个不相同字符的位置
int[] charCount = new int[26];//统计每个字符出现的次数
boolean isRepeat = false;//标记是否有重复字符出现
for (int i = 0; i < charsA.length; i++) {
if (!isRepeat) {
if (charCount[charsA[i] - 'a'] > 0) isRepeat = true;//有重复字符出现
else charCount[charsA[i] - 'a']++;
}
if (charsA[i] != charsB[i]) {//有不同字符出现
if (count >= 2) return false;//出现了三个不同字符,返回false
indexs[count++] = i;//记录不同字符的位置
}
}
if (count == 0) return isRepeat;
else if (count == 1) return false;
else return charsA[indexs[0]] == charsB[indexs[1]] && charsA[indexs[1]] == charsB[indexs[0]];
}