leetcode-859-easy
Buddy Strings
思路一: 两个字符是 Buddy Strings 的完全分类
- 字符不一样 && 只存在两个位置交换的字符
- 字符一样 && 存在重复的字符
按照上面的分类,记录两个不同位置的下标和统计出现字符的情况
public boolean buddyStrings(String s, String goal) {
if (s.length() != goal.length()) return false;
int[] count = new int[26];
boolean find = false;
int first = -1;
int second = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
if (first == -1) {
first = i;
continue;
}
if (second == -1) {
second = i;
} else {
return false;
}
}
count[s.charAt(i) - 'a']++;
if (count[s.charAt(i) - 'a'] >= 2) find = true;
}
if (first == -1 && second == -1 && find) return true;
return first != -1 && second != -1 &&
s.charAt(second) == goal.charAt(first)
&& s.charAt(first) == goal.charAt(second);
}

浙公网安备 33010602011771号