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;
    }
  • 相关阅读:
    03-链表
    23-自定义用户模型
    01-使用pipenv管理项目环境
    10-多线程、多进程和线程池编程
    17-Python执行JS代码--PyExecJS、PyV8、Js2Py
    09-Python-Socket编程
    08-迭代器和生成器
    07-元类编程
    06-对象引用、可变性和垃圾回收
    05-深入python的set和dict
  • 原文地址:https://www.cnblogs.com/learning-c/p/9787578.html
Copyright © 2011-2022 走看看