-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
51 lines (46 loc) · 1.35 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// https://leetcode.com/problems/buddy-strings
class Solution {
public boolean buddyStrings(String A, String B) {
if(A.length() != B.length()) return false;
int j = -1, k = -1;
int n = A.length();
for(int i=0;i<n;i++){
if(A.charAt(i) != B.charAt(i)){
if(j == -1){
j = i;
}else{
k = i;
}
}
}
// System.out.println(j + " " + k);
if(k == -1 && j == -1){
int freq[] = new int[26];
for(int i=0;i<n;i++){
freq[A.charAt(i) - 'a'] ++;
if(freq[A.charAt(i) - 'a'] > 1) return true;
}
return false;
}else if(k == -1){
return false;
}
for(int i=0;i<n;i++){
if(A.charAt(i) != B.charAt(i)){
if(i == j){
if(A.charAt(k) == B.charAt(i)){
continue;
}
return false;
}else if(i == k){
if(A.charAt(j) == B.charAt(i)){
continue;
}
return false;
}else{
return false;
}
}
}
return true;
}
}