[LeetCode] Check if One String Swap Can Make Strings Equal

1790. Check if One String Swap Can Make Strings Equal

You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.

Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool areAlmostEqual(string s1, string s2) {
int diff = 0, counter[26]{0,};
for(int i = 0; i < s1.length() and diff <= 2; i++) {
if(s1[i] != s2[i]) {
diff++;
counter[s1[i]-'a']++;
counter[s2[i]-'a']--;
}
}
if(diff == 0) return true;
if(diff == 2) {
for(int i = 0; i < 26; i++)
if(counter[i]) return false;
return true;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/28/PS/LeetCode/check-if-one-string-swap-can-make-strings-equal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.