-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuddyStrings.java
42 lines (41 loc) · 1.53 KB
/
BuddyStrings.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
public class BuddyStrings {
public boolean buddyStrings(String s, String goal) {
if(s == null || goal == null || s.length() != goal.length() || s.length() < 2){
return false;
}
if(s.equals(goal)){
int[] map = new int[26];
for(int i = 0; i < s.length(); i++){
if(map[s.charAt(i) - 'a'] == 1){
return true;
}else{
map[s.charAt(i) - 'a'] = 1;
}
}
}
char[] s1 = s.toCharArray();
char[] s2 = goal.toCharArray();
char s1_1 = '1', s1_2 = '2', s2_1 = '3', s2_2 = '4';
boolean found1stDiff = false;
boolean found2ndDiff = false;
for(int i = 0; i < s1.length; i++){
if(s1[i] != s2[i]){
if(!found1stDiff){
found1stDiff = true;
s1_1 = s1[i];
s2_1 = s2[i];
}else if(!found2ndDiff){
found2ndDiff = true;
s1_2 = s1[i];
s2_2 = s2[i];
if(s1_2 != s2_1 || s1_1 != s2_2){
return false;
}
}else{
return false;
}
}
}
return found1stDiff && found2ndDiff;
}
}