You are given an array A
of strings.
A move onto S
consists of swapping any two even indexed characters of S
, or any two odd indexed characters of S
.
Two strings S
and T
are special-equivalent if after any number of moves onto S
, S == T
.
For example, S = "zzxy"
and T = "xyzz"
are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz"
that swap S[0]
and S[2]
, then S[1]
and S[3]
.
Now, a group of special-equivalent strings from A
is a non-empty subset of A such that:
1.Every pair of strings in the group are special equivalent, and;
2.The group is the largest size possible (ie., there isn't a string S not in the group such that S is special equivalent to every string in the group)
Return the number of groups of special-equivalent strings from A
.
Example:
Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation:
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.
The other two groups are ["xyzz", "zzxy"] and ["zzyx"]. Note that in particular, "zzxy" is not special equivalent to "zzyx".
Approach:
C++
#include <bits/stdc++.h>using namespace std;int numSpecialEquivGroups(vector<string> &A){unordered_set<string> set;for (auto &str : A){string upper = "", lower = "";for (int i = 0; i < str.size(); ++i){if (i & 1){lower += str[i];}else{upper += str[i];}}sort(lower.begin(), lower.end());sort(upper.begin(), upper.end());str = lower + upper;if (set.find(str) == set.end()){set.insert(str);}}return set.size();}int main(){vector<string> A = {"abcd", "cdab", "cbad","xyzz", "zzxy", "zzyx"};cout << numSpecialEquivGroups(A);return 0;}
No comments:
Post a Comment