[LeetCode] 893. Groups of Special-Equivalent Strings 特殊字符串的羣組



You are given an array A of strings.html

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

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

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.app

Example 1:ui

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

Example 2:code

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

Example 3:htm

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

Example 4:blog

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.



這道題定義了一種特殊相等的關係,就是說對於一個字符串,假如其偶數位字符之間能夠互相交換,且其奇數位字符之間能夠互相交換,交換後若能跟另外一個字符串相等,則這兩個字符串是特殊相等的關係。如今給了咱們一個字符串數組,將全部特殊相等的字符串放到一個羣組中,問最終能有幾個不一樣的羣組。最開始的時候博主沒仔細審題,覺得是隨意交換字母,就直接對每一個單詞進行排序,而後扔到一個 HashSet 中就好了。後來發現只能是奇偶位上互相交換,因而只能現先將奇偶位上的字母分別抽離出來,而後再進行分別排序,以後再合併起來組成一個新的字符串,再丟到 HashSet 中便可,利用 HashSet 的自動去重複功能,這樣最終留下來的就是不一樣的羣組了,參見代碼以下:


class Solution {
public:
    int numSpecialEquivGroups(vector<string>& A) {
        unordered_set<string> st;
        for (string word : A) {
            string even, odd;
            for (int i = 0; i < word.size(); ++i) {
                if (i % 2 == 0) even += word[i];
                else odd += word[i];
            }
            sort(even.begin(), even.end());
            sort(odd.begin(), odd.end());
            st.insert(even + odd);
        }
        return st.size();
    }
};



Github 同步地址:

https://github.com/grandyang/leetcode/issues/893



參考資料:

https://leetcode.com/problems/groups-of-special-equivalent-strings/

https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/163413/Java-Concise-Set-Solution

https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/163412/C%2B%2B-Simple-Solution

https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/163891/C%2B%2B-Create-a-signature-for-each-string



LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索