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 ofgroups of special-equivalent strings from _words.
Input: words =["abcd","cdab","cbad","xyzz","zzxy","zzyx"]Output: 3Explanation:
One group is["abcd","cdab","cbad"], since they are all pairwise special equivalent, and none of the other strings is 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".
Two strings are special-equivalent if, after any number of swaps of even or odd indexed characters, their even and odd indexed characters can be rearranged independently. Thus, the canonical form is obtained by sorting the even and odd indexed characters separately.
classSolution {
publicintnumSpecialEquivGroups(String[] words) {
Set<String> s =new HashSet<>();
for (String w : words) {
StringBuilder even =new StringBuilder(), odd =new StringBuilder();
for (int i = 0; i < w.length(); i++) {
if (i % 2 == 0) even.append(w.charAt(i));
else odd.append(w.charAt(i));
}
char[] e = even.toString().toCharArray(), o = odd.toString().toCharArray();
Arrays.sort(e);
Arrays.sort(o);
s.add(new String(e) +new String(o));
}
return s.size();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funnumSpecialEquivGroups(words: Array<String>): Int {
val s = mutableSetOf<String>()
for (w in words) {
val even = mutableListOf<Char>()
val odd = mutableListOf<Char>()
for (i in w.indices) {
if (i % 2==0) even.add(w[i]) else odd.add(w[i])
}
s.add(even.sorted().joinToString("") + odd.sorted().joinToString(""))
}
return s.size
}
}
1
2
3
4
5
6
7
8
classSolution:
defnumSpecialEquivGroups(self, words: list[str]) -> int:
s = set()
for w in words:
even = sorted(w[::2])
odd = sorted(w[1::2])
s.add((''.join(even), ''.join(odd)))
return len(s)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::collections::HashSet;
impl Solution {
pubfnnum_special_equiv_groups(words: Vec<String>) -> i32 {
letmut s = HashSet::new();
for w in words {
let (mut even, mut odd) = (Vec::new(), Vec::new());
for (i, c) in w.chars().enumerate() {
if i %2==0 { even.push(c); } else { odd.push(c); }
}
even.sort_unstable();
odd.sort_unstable();
s.insert((even, odd));
}
s.len() asi32 }
}