893. Groups of Special-Equivalent Strings

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 string。

 

#include<vector>
#include <cstdlib>
#include<iostream>
#include <unordered_set>
#include <algorithm>

using namespace std;

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


int main() {
    Solution solution;
    vector<string> A1 = {"abcd", "cdab", "adcb", "cbad"};
    vector<string> A2 = {"abc", "acb", "bac", "bca", "cab", "cba"};
    int res1 = solution.numSpecialEquivGroups(A1);
    int res2 = solution.numSpecialEquivGroups(A2);

    std::cout << "res1: " << res1 << endl;
    std::cout << "res2: " << res2 << endl;
    return 0;
}

 

posted @ 2018-10-14 19:43  hopskin1  阅读(310)  评论(0编辑  收藏  举报