yysue

## Question

859. Buddy Strings

## Solution

``````diff 记录不同字符数

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;
}
``````

### 评论(3)

#### 引用来自“z7k”的评论

return false ;
}。如果直接for (int i = 0; i < A.length(); i++) 万一A比B长岂不是B.charAt(i)就会报错了。

#### 引用来自“yysue”的评论

if (A.length() != B.length()) return false; 这个条件就把你说的那种情况给过滤掉了

class Solution {
public static boolean buddyStrings(String A, String B) {
int len = A.length();
//长度不同肯定是不行
if(len != B.length()){
return false;
}
int[] diff = new int[len];
//如果内容一样，则必须有重复字母
if(B.equals(A)){
Set set = new HashSet<>();
for(int i = 0; i < len;i++){
}
return set.size() < len;
}
int j = 0;
//如果内容不一样，只能允许两处字符不同，并且互相调换顺序还得一样才行
for(int i = 0; i < len; i++){
if(A.charAt(i) != B.charAt(i)){
diff[j++] = i;
}
//若多于两处不同，则可直接返回false
if(j > 2){
return false;
}
}
return j == 2 && A.charAt(diff[0]) == B.charAt(diff[1]) && A.charAt(diff[1]) == B.charAt(diff[0]);
}
}

#### 引用来自“z7k”的评论

return false ;
}。如果直接for (int i = 0; i < A.length(); i++) 万一A比B长岂不是B.charAt(i)就会报错了。
if (A.length() != B.length()) return false; 这个条件就把你说的那种情况给过滤掉了

return false ;
}。如果直接for (int i = 0; i < A.length(); i++) 万一A比B长岂不是B.charAt(i)就会报错了。
LeetCode.859-伙伴字符串（Buddy Strings）

05/10
0
0
IsomorphicStrings(leetcode205)

Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be r......

woshixin
2018/11/29
7
0
Find All Anagrams in a String(leetcode438)

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s a......

woshixin
02/12
3
0

2018/01/02
0
0
Find the Difference(leetcode389)

Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the......

woshixin
01/09
4
0

Alex_Java
32分钟前
5
0
Java8新特性时间日期库DateTime API及示例

Java8新特性的功能已经更新了不少篇幅了，今天重点讲解时间日期库中DateTime相关处理。同样的，如果你现在依旧在项目中使用传统Date、Calendar和SimpleDateFormat等API来处理日期相关操作，这...

42分钟前
7
0

xintaiideas

6
0

6
0

5
0