Buddy Strings LeetCode solution in C++

1
class Solution {
2
public:
3
// In case string is duplicated, check if string has any duplicate letters
4
bool dupeCase(string s) {
5
unordered_set<char> letters;
6
for (auto it : s) {
7
if (letters.count(it)) { // Found dupe letter (they can be swapped)
8
return true;
9
} else {
10
letters.insert(it);
11
}
12
}
13
return false; // all letters unique
14
}
15

16
bool buddyStrings(string s, string goal) {
17
// check len
18
if (goal.length() != s.length()) return false;
19
// If strings are the same, use diff. method
20
if (s == goal) return dupeCase(s);
21
// Track index of differences
22
vector<int> diff;
23
for (int i = 0; i < s.length(); i++) {
24
if (s[i] != goal[i]) { // If diff found
25
if (diff.size() > 2) { // If this is third diff, return false
26
return false;
27
} else { // If not store in diff array
28
diff.push_back(i);
29
}
30
}
31
}
32
// If only one diff found, return false
33
if (diff.size() == 1) return false;
34
// else return if swap works
35
return (s[diff[0]] == goal[diff[1]] && s[diff[1]] == goal[diff[0]]);
36
}
37
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0