[LeetCode] Determine if Two Strings Are Close

1657. Determine if Two Strings Are Close

Two strings are considered close if you can attain one from the other using the following operations:

  • Operation 1: Swap any two existing characters.
  • For example, abcde -> aecdb
  • Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
  • For example, aacabb -> bbcbaa (all a’s turn into b’s, and all b’s turn into a’s)
    You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool closeStrings(string word1, string word2) {
if(word1.size() != word2.size()) return false;
vector<int> w1(26), w2(26);
for(int i = 0; i < word1.size(); i++) {
w1[word1[i]-'a']++;
w2[word2[i]-'a']++;
}

for(int i = 0; i < 26; i++) {
if((w1[i] == 0 and w2[i] != 0) or (w1[i] != 0 and w2[i] == 0)) return false;
}

sort(w1.begin(),w1.end());
sort(w2.begin(),w2.end());

return w1 == w2;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/29/PS/LeetCode/determine-if-two-strings-are-close/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.