forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuddy Strings.java
More file actions
25 lines (21 loc) · 767 Bytes
/
Buddy Strings.java
File metadata and controls
25 lines (21 loc) · 767 Bytes
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
class Solution {
public static boolean buddyStrings(String A, String B) {
if (A.length() != B.length() || A.length() <= 1 || B.length() <= 1) {
return false;
}
if (A.equals(B)) {
Set<Character> s = new HashSet<Character>();
for (char c : A.toCharArray()) {
s.add(c);
}
return s.size() < A.length();
}
List<Integer> dif = new ArrayList<>();
for (int i = 0; i < A.length(); ++i) {
if (A.charAt(i) != B.charAt(i)) {
dif.add(i);
}
}
return dif.size() == 2 && A.charAt(dif.get(0)) == B.charAt(dif.get(1)) && A.charAt(dif.get(1)) == B.charAt(dif.get(0));
}
}