-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuddyStrings.java
More file actions
39 lines (30 loc) · 1.07 KB
/
Copy pathBuddyStrings.java
File metadata and controls
39 lines (30 loc) · 1.07 KB
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
package LeetcodePractice;
public class BuddyStrings {
public static boolean buddyStrings(String s, String goal) {
if (s.length() != goal.length()) return false;
if (s.equals(goal)) {
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
if (count[c - 'a'] > 1) return true;
}
return false;
}
int first = -1, second = -1, diffCount = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
diffCount++;
if (first == -1) first = i;
else second = i;
}
}
return diffCount == 2 &&
s.charAt(first) == goal.charAt(second) &&
s.charAt(second) == goal.charAt(first);
}
public static void main(String[] args) {
System.out.println(buddyStrings("ab", "ba"));
System.out.println(buddyStrings("ab", "ab"));
System.out.println(buddyStrings("aa", "aa"));
}
}