[LeetCode] Groups of Special-Equivalent Strings

893. Groups of Special-Equivalent Strings

You are given an array of strings of the same length words.

In one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i].

Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j].

  • For example, words[i] = “zzxy” and words[j] = “xyzz” are special-equivalent because we may make the moves “zzxy” -> “xzzy” -> “xyzz”.

A group of special-equivalent strings from words is a non-empty subset of words such that:

  • Every pair of strings in the group are special equivalent, and
  • The group is the largest size possible (i.e., there is not a string words[i] not in the group such that words[i] is special-equivalent to every string in the group).

Return the number of groups of special-equivalent strings from words.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
string convert(string s) {
string odd = "", even = "";
for(int i = 0; i < s.length(); i++) {
if(i & 1) odd.push_back(s[i]);
else even.push_back(s[i]);
}
sort(begin(odd), end(odd));
sort(begin(even), end(even));
return odd + even;
}
public:
int numSpecialEquivGroups(vector<string>& words) {
unordered_set<string> us;
for(auto& w : words) {
us.insert(convert(w));
}
return us.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/13/PS/LeetCode/groups-of-special-equivalent-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.