1. 程式人生 > >893. Groups of Special-Equivalent Strings(python+cpp)

893. Groups of Special-Equivalent Strings(python+cpp)

題目:

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: 3groups [“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.

解釋: 不太好解釋,看例項就懂了。

python程式碼:

class Solution(object):
    def numSpecialEquivGroups(self, A):
        """
        :type A: List[str]
        :rtype: int
        """
        return len(set(''.join(sorted(s[0::2]))+''.join(sorted(s[1::2]) ) for s  in A )) 

c++程式碼:

#include<set>
#include<string>
#icnlude
using namespace std;
class Solution {
public:
    int numSpecialEquivGroups(vector<string>& A) {
        set<string> _set;
        for (auto s:A)
        {
            string tmp1="";
            string tmp2="";
            for (int i=0;i<s.size();i++)
            {
                if(i%2)
                    tmp2+=s[i];
                else
                    tmp1+=s[i];
            }
            sort(tmp1.begin(),tmp1.end());
            sort(tmp2.begin(),tmp2.end());
            _set.insert(tmp1+tmp2);
        }
        return _set.size();
    }
};

總結: 學會使用stl中的set,string,sort等庫函式。