You are given an arrayA
of strings.
Two stringsS
andT
are special-equivalent if after any number ofmoves, S == T.
A _move _consists of choosing two indicesi
andj
withi % 2 == j % 2
, and swappingS[i]
withS[j]
.
Now, agroup of special-equivalent strings fromA
is a non-empty subset S ofA
such that any string not in S is not special-equivalent with any string in S.
Return the number of groups of special-equivalent strings fromA
.
Note:
1 <= A.length <= 1000
1 <= A[i].length <= 20
- All
A[i]
have the same length. - All
A[i]
consist of only lowercase letters.
这个题就是按照规则统计奇数index上的所有字符出现次数和偶数index上所有字符出现的次数,将所有equivalent的字符串map到同一个字符串,再统计map之后的字符串个数
class Solution {
public int numSpecialEquivGroups(String[] A) {
if(A == null || A.length == 0)
return 0;
HashSet<String> set = new HashSet<String>();
for(String s: A) {
set.add(encode(s));
}
return set.size();
}
public String encode(String s) {
StringBuilder res = new StringBuilder();
char[] even = new char[26];
char[] odd = new char[26];
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(i % 2 == 0) {
even[c - 'a']++;
} else{
odd[c - 'a']++;
}
}
for(int i = 0; i < 26; i++) {
if(even[i] != 0)
res.append((char) ('a' + i)).append(even[i]);
}
res.append('|');
for(int i = 0; i < 26; i++) {
if(odd[i] != 0)
res.append((char) ('a' + i)).append(odd[i]);
}
return res.toString();
}
}