Title:Buddy Strings 859
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/buddy-strings/
1. 见代码注释
时间复杂度:O(n),多次一层for循环。
空间复杂度:O(n),申请26个长度的数组。
/**
* 两种情况:
* 1、A和B一样,但是A中有至少一个字符是重复了两次,这样这个字符可以交换(A[i]==B[i]==A[j]==B[j])
* 2、A和B不一样,但是A可以交换两个不同的字符,使得A和B一样(A[i]==B[j]&&A[j]==B[i])
* @param A
* @param B
* @return
*/
public static boolean buddyStrings(String A, String B) {
if (A.length() != B.length()) {
return false;
}
if (A.equals(B)) {
int count[] = new int[26];
for (int i = 0; i < A.length(); i++) {
count[A.charAt(i) - 'a']++;
}
for (int i = 0; i < count.length; i++) {
if (count[i] > 1) {
return true;
}
}
return false;
}
else {
int one = -1;
int two = -1;
for (int i = 0; i < A.length(); i++) {
if (A.charAt(i) != B.charAt(i)) {
if (one == -1) {
one = i;
}
else if (two == -1) {
two = i;
}
else {
return false;
}
}
}
if (two != -1 && A.charAt(one) == B.charAt(two) && A.charAt(two) == B.charAt(one)) {
return true;
}
else {
return false;
}
}
}