-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buddyStrings.cpp
37 lines (28 loc) · 937 Bytes
/
buddyStrings.cpp
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
class Solution {
public:
bool buddyStrings(string A, string B) {
if(A.size() != B.size()) return false;
unordered_set<char> setA, setB;
bool repeatA = false, repeatB = false;
vector<int> pos;
int n = A.size();
for(int i = 0; i < n; ++i) {
char a = A.at(i);
char b = B.at(i);
if(setA.find(a) != setA.end())
repeatA = true;
if(setB.find(b) != setB.end())
repeatB = true;
setA.insert(a);
setB.insert(b);
if(a != b) pos.push_back(i);
}
if(pos.size() == 2) {
if(A[pos[0]] == B[pos[1]] && A[pos[1]] == B[pos[0]])
return true;
}
if(A == B && repeatA && repeatB)
return true;
return false;
}
};