-
Notifications
You must be signed in to change notification settings - Fork 0
/
buddy_strings.c++
52 lines (42 loc) · 1.02 KB
/
buddy_strings.c++
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
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
bool buddyStrings(string s, string goal)
{
unordered_map<char, int> freq;
int diff = 0, swaps[3];
if (s.length() != goal.length() or s.length() == 1 or goal.length() == 1)
return false;
if (s == goal)
{
for (int index = 0; index < s.length(); index++)
freq[s.at(index)]++;
for (int index = 0; index < s.length(); index++)
if (freq[s.at(index)] > 1)
return true;
return false;
}
for (int index = 0; index < s.length(); index++)
{
if (s.at(index) != goal.at(index))
{
swaps[diff] = index;
diff++;
}
if (diff > 2)
return false;
}
if(diff <= 1)
return false;
char temp = s[swaps[0]];
s[swaps[0]] = s[swaps[1]];
s[swaps[1]] = temp;
if (s == goal)
return true;
return false;
}
int main()
{
cout << buddyStrings("ab", "ab") << endl;
}