Skip to content

Commit f9551cd

Browse files
committed
storing location of mismatch and checking if replacing equals other string
1 parent 079c036 commit f9551cd

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Strings/buddyStrings.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public boolean buddyStrings(String A, String B) {
3+
if (A.length() != B.length()) {
4+
return false;
5+
}
6+
HashSet<Character> setA = new HashSet<>();
7+
HashSet<Character> setB = new HashSet<>();
8+
boolean dupA = false;
9+
boolean dupB = false;
10+
List<Integer> mismatch = new ArrayList<>();
11+
for (int i=0; i<A.length(); i++) {
12+
if (setA.contains(A.charAt(i))) {
13+
dupA = true;
14+
}
15+
if (setB.contains(B.charAt(i))) {
16+
dupB = true;
17+
}
18+
19+
if(A.charAt(i) != B.charAt(i)) {
20+
mismatch.add(i);
21+
}
22+
setA.add(A.charAt(i));
23+
setB.add(B.charAt(i));
24+
}
25+
if (mismatch.size() == 2) {
26+
if ((A.charAt(mismatch.get(0)) == B.charAt(mismatch.get(1)))&& (A.charAt(mismatch.get(1)) == B.charAt(mismatch.get(0)))) {
27+
return true;
28+
}
29+
}
30+
if (dupA && dupB && A.equals(B)) {
31+
return true;
32+
}
33+
return false;
34+
}
35+
}

0 commit comments

Comments
 (0)