zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    Ubuntu学习
    Django之 Views组件
    Django之 admin组件
    Django之 Models组件
    Django之 url组件
    递归
    python 之 编码
    Python 之 Restful API设计规范
    Django之实现登录随机验证码
    git &github 快速入门
  • 原文地址:https://www.cnblogs.com/learning-c/p/9787578.html
Copyright © 2011-2022 走看看