Check if One String Swap Can Make Strings Equal LeetCode solution in C++

1
/*
2
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/
3

4
Find the number of positions which are different.
5
Now the strings can be made equal only if there are 0
6
different positions or 2 different positions and there are
7
chars on those positions which when swaped will make the
8
strings equal.
9
TC: O(N)
10
SC: O(1), At most 2 values are put in the diff_pos vector
11
*/
12

13
class Solution {
14
public:
15
bool areAlmostEqual(string s1, string s2) {
16
// find the number of diff positions
17
vector<int> diff_pos;
18
for (int i = 0; i < s1.size(); i++) {
19
if (s1[i] != s2[i]) diff_pos.emplace_back(i);
20
// If there are more than 2 char positions that differ,
21
// the single swap op cannot anyway make the two strings equal
22
if (diff_pos.size() > 2) return false;
23
}
24
// when the chars are exactly the same
25
if (diff_pos.empty()) return true;
26
// only one pair of diff positions, check if swapping makes them equal
27
if (diff_pos.size() == 2) swap(s1[diff_pos[0]], s1[diff_pos[1]]);
28

29
return s1 == s2;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0