Question
Solution
题目大意:
两个字符串,其中一个字符串任意两个字符互换后与另一个字符串相等,只能互换一次
思路:
diff 记录不同字符数
两个字符串长度不同 return false
两个字符串长度相同:
abc abd 无重复,diff == 1 ca[3] != cb[3] return false
abc abc 无重复,diff == 0 return false
ab ba 无重复,diff == 2 return true
aa aa aa重复,diff == 0 return true
aabc aabc aa重复,diff == 0 return true
aacb aabc aa重复,diff == 2 return true
Java实现:
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length()) return false;
int[] ca = new int[26];
int[] cb = new int[26];
int diff = 0;
for (int i = 0; i < A.length(); i++) {
ca[A.charAt(i) - 'a']++;
cb[B.charAt(i) - 'a']++;
if (A.charAt(i) != B.charAt(i)) diff++;
}
for (int i = 0; i < ca.length; i++) {
if (diff == 0 && ca[i] > 1) return true;
if (ca[i] != cb[i]) return false;
}
return diff == 2;
}