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等库函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值