-
Notifications
You must be signed in to change notification settings - Fork 0
/
buddy_strings.cpp
68 lines (51 loc) · 1.47 KB
/
buddy_strings.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Solution {
public:
bool buddyStrings(string s, string goal) {
if(s.length() != goal.length()){
return false;
}
if(s == goal){
unordered_map<char, int>mp;
for(int i = 0; i< s.length(); i++){
mp[s[i]]++;
}
unordered_map<char, int>:: iterator it;
for(auto it = mp.begin(); it != mp.end(); it++){
if(it->second > 1){
return true;
}
}
return false;
}
int count = 0;
string s1 = s;
string g1 = goal;
bool flag = false;
bool check = true;
for(int i=0; i< s.length(); i++){
if(s[i] != goal[i]){
flag = true;
if(count == 0){
s1.clear();
g1.clear();
}
s1.push_back(s[i]);
g1.push_back(goal[i]);
count++;
if(count > 2){
return false;
}
}
}
if(flag){
if(count != 2){
return false;
}
}
swap(s1[0], s1[1]);
if(s1 == g1){
return true;
}
return false;
}
};