859. Buddy Strings - LeetCode
Posted okokabcd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了859. Buddy Strings - LeetCode相关的知识,希望对你有一定的参考价值。
Question
Solution
题目大意:
两个字符串,其中一个字符串任意两个字符互换后与另一个字符串相等,只能互换一次
思路:
diff 记录不同字符数
长度不同
abc abd 无重复且diff == 1 ca[3] != cb[3]
abc abc 无重复且diff > 2
aa aa aa重复
ab ba diff == 2
aabc aabc aa重复
aacb aabc diff == 2
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;
}
以上是关于859. Buddy Strings - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode.859-伙伴字符串(Buddy Strings)
leetcode 859. 亲密字符串(Buddy Strings)
859. Buddy Strings (wrong 4 times so many cases to test and consider) if else**