[leetcode] problem 893 – groups of special-equivalent strings

You are given an array A of strings.

Two strings S and T are special-equivalent if after any number of moves, S == T.

A move consists of choosing two indices i and j with i % 2 == j % 2, and swapping S[i] with S[j].

Now, a group of special-equivalent strings from A is a non-empty subset S of A 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 from A.

Example

No.1

Input: [“a”,”b”,”c”,”a”,”c”,”c”]

Output: 3

Explanation: 3 groups [“a”,”a”], [“b”], [“c”,”c”,”c”]

No.2

Input: [“aa”,”bb”,”ab”,”ba”]

Output: 4

Explanation: 4 groups [“aa”], [“bb”], [“ab”], [“ba”]

No.3

Input: [“abc”,”acb”,”bac”,”bca”,”cab”,”cba”]

Output: 3

Explanation: 3 groups [“abc”,”cba”], [“acb”,”bca”], [“bac”,”cab”]

No.4

Input: [“abcd”,”cdab”,”adcb”,”cbad”]

Output: 1

Explanation: 1 group [“abcd”,”cdab”,”adcb”,”cbad”]

Note

  1. 1 <= A.length <= 1000
  2. 1 <= A[i].length <= 20
  3. All A[i] have the same length.
  4. All A[i] consist of only lowercase letters.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public int (String[] A) {
Set<String> set = new HashSet<>();

for (String str : A) {
int n = str.length();
char[] odd = new char[n / 2];
char[] even = new char[(n + 1) / 2];

for (int i = 0; i < n; i++) {
if (i % 2 == 0)
even[i / 2] = str.charAt(i);
else
odd[i / 2] = str.charAt(i);
}

Arrays.sort(even);
Arrays.sort(odd);
set.add(String.valueOf(odd) + String.valueOf(even));
}

return set.size();
}