You are given an array A of strings.

A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.

Two strings S and T are special-equivalent if after any number of moves onto S, S == T.

For example, S = "zzxy" and T = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz" that swap S[0] and S[2], then S[1] and S[3].

Now, a group of special-equivalent strings from A is a non-empty subset of A such that:

Every pair of strings in the group are special equivalent, and;
The group is the largest size possible (ie., there isn't a string S not in the group such that S is special equivalent to every string in the group)
Return the number of groups of special-equivalent strings from A.


Example 1:

Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation: 
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.

The other two groups are ["xyzz", "zzxy"] and ["zzyx"].  Note that in particular, "zzxy" is not special equivalent to "zzyx".
Example 2:

Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3


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.

好久没有写题目了,做Easy的题目,有点生疏,没有找回状态。

首先这题主要定义了一种字符串,这种字符串假设两个偶数索引或者奇数索引之间进行调换后能相等,那么它们就是题目中所定义的字符串。给一串字符串,看看能够有多少种类型的该字符串。

这题其实很直接,将字符串的奇数,偶数分别提取出来组成新的字符串并进行排序,看看有多少这种字符串即可,代码如下:

class GroupsOfSpecialEquivalentStrings : public Solution {
public:
    virtual void Execute() {
        vector<string> strs;
        std::cout << "Case 1: " << numSpecialEquivGroups(vector<string>{"abcd","cdab","cbad","xyzz","zzxy","zzyx"}) << std::endl;
    }

    void regen(const std::string &l, string &pa) {
        int index = 0;
        pa = l;
        for (auto &v : l) {
            pa[(index % 2 != 0 ? 0 : l.size() / 2) + index / 2] = v;
            index++;
        }
        std::sort(pa.begin(), pa.begin() + l.size() / 2);
        std::sort(pa.begin() + l.size() / 2, pa.end());
    }

    int numSpecialEquivGroups(const vector<string> &A) {
      unordered_set<string> groups;

      for (auto &v : A) {
        std::string pattern;
        regen(v, pattern);
        groups.insert(std::move(pattern));
      }

      return groups.size();
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day