1. 程式人生 > >LeetCode-Groups of Special-Equivalent Strings

LeetCode-Groups of Special-Equivalent Strings

Description: 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 1:

Input: ["a","b","c","a","c","c"]
Output: 3
Explanation: 3 groups ["a","a"], ["b"], ["c","c","c"]

Example 2:

Input: ["aa","bb","ab","ba"]
Output: 4
Explanation: 4 groups ["aa"], ["bb"], ["ab"], ["ba"]

Example 3:

Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3
Explanation: 3 groups ["abc","cba"], ["acb","bca"], ["bac","cab"]

Example 4:

Input: ["abcd","cdab","adcb","cbad"]
Output: 1
Explanation: 1 group ["abcd","cdab","adcb","cbad"]

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.

題意:給定一個字串陣列,找出一共有多少組的special-equivalent字串,其定義是字串S中的字元經過交換S[i]與S[j](i % 2 == j % 2)後於字串T相同;

解法:這道題主要的問題就在於怎麼判斷兩個字串是否為special-equivalent字串;交換的條件是i % 2 == j % 2,也就是說交換的是字串中的奇數位或者是偶數位;因此,我們可以將字串中的奇數位字元和偶數位字元組成兩個新的字串S1和S2,同樣的對另外一個字串做一樣的操作得到字串T1和T2,如果兩個字串為special-equivalent,那麼應當滿足

  • Arrays.sort(S1).equals(Arrays.sort(T1))
  • Arrays.sort(S2).equals(Arrays.sort(T2))
Java
class Solution {
    public int numSpecialEquivGroups(String[] A) {
        boolean[] visited = new boolean[A.length];
        int cnt = 0;
        for (int i = 0; i < A.length; i++) {
            boolean group = false;
            if (visited[i]) continue;
            for (int j = i + 1; j < A.length; j++) {
                if (!visited[j] && specialEquivalent(A[i], A[j])) {
                    group = true;
                    visited[j] = true;
                }
            }
            cnt++;
        }
        return cnt;
    }
    
    private boolean specialEquivalent (String S, String T) {
        char[] S1 = new char[S.length() / 2 + 1];
        char[] S2 = new char[S.length() / 2 + 1];
        char[] T1 = new char[T.length() / 2 + 1];
        char[] T2 = new char[T.length() / 2 + 1];
        for (int i = 0; i < S.length(); i++) {
            if (i % 2 == 0) S1[i / 2] = S.charAt(i);
            else S2[i / 2]= S.charAt(i);
        }
        for (int i = 0; i < T.length(); i++) {
            if (i % 2 == 0) T1[i / 2] = T.charAt(i);
            else T2[i / 2]= T.charAt(i);
        }
        Arrays.sort(S1);
        Arrays.sort(S2);
        Arrays.sort(T1);
        Arrays.sort(T2);
        return Arrays.toString(S1).equals(Arrays.toString(T1)) &&
               Arrays.toString(S2).equals(Arrays.toString(T2)) ? true : false;
    }
}