标签:public ems 不同 href length code java boolean question
题目大意:
两个字符串,其中一个字符串任意两个字符互换后与另一个字符串相等,只能互换一次
思路:
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;
}
标签:public ems 不同 href length code java boolean question
原文地址:https://www.cnblogs.com/okokabcd/p/9532321.html