[LeetCode] Buddy Strings

859. Buddy Strings

Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].

  • For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool buddyStrings(string s, string goal) {
if(s.length() != goal.length()) return false;
vector<int> bad;
unordered_set<char> us;
for(int i = 0; i < s.length(); i++) {
if(s[i] != goal[i]) {
bad.push_back(i);
if(bad.size() > 2) return false;
} else us.insert(s[i]);
}
if(bad.size() == 0) return us.size() != s.length();
if(bad.size() != 2) return false;
swap(s[bad[0]], s[bad[1]]);
return s == goal;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/03/PS/LeetCode/buddy-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.