-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuddystrings.cpp
More file actions
28 lines (24 loc) · 807 Bytes
/
buddystrings.cpp
File metadata and controls
28 lines (24 loc) · 807 Bytes
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
class Solution {
public:
bool buddyStrings(string s, string goal) {
if (s.length() != goal.length()) return false;
// Case 1: Strings are identical -> must have duplicate character
if (s == goal) {
vector<int> freq(26, 0);
for (char c : s) {
freq[c - 'a']++;
if (freq[c - 'a'] > 1) return true;
}
return false;
}
// Case 2: Strings differ -> must differ at exactly two positions
vector<int> diff;
for (int i = 0; i < s.length(); i++) {
if (s[i] != goal[i]) diff.push_back(i);
}
if (diff.size() != 2) return false;
// Check swap
return s[diff[0]] == goal[diff[1]] &&
s[diff[1]] == goal[diff[0]];
}
};