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 jwith 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: 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 <= 10001 <= A[i].length <= 20- All
A[i]have the same length. - All
A[i]consist of only lowercase letters.
這道題定義了一種特殊相等的關系,就是說對於一個字符串,假如其偶數位字符之間可以互相交換,且其奇數位字符之間可以互相交換,交換后若能跟另一個字符串相等,則這兩個字符串是特殊相等的關系。現在給了我們一個字符串數組,將所有特殊相等的字符串放到一個群組中,問最終能有幾個不同的群組。最開始的時候博主沒仔細審題,以為是隨意交換字母,就直接對每個單詞進行排序,然后扔到一個 HashSet 中就行了。后來發現只能是奇偶位上互相交換,於是只能現先將奇偶位上的字母分別抽離出來,然后再進行分別排序,之后再合並起來組成一個新的字符串,再丟到 HashSet 中即可,利用 HashSet 的自動去重復功能,這樣最終留下來的就是不同的群組了,參見代碼如下:
class Solution {
public:
int numSpecialEquivGroups(vector<string>& A) {
unordered_set<string> st;
for (string word : A) {
string even, odd;
for (int i = 0; i < word.size(); ++i) {
if (i % 2 == 0) even += word[i];
else odd += word[i];
}
sort(even.begin(), even.end());
sort(odd.begin(), odd.end());
st.insert(even + odd);
}
return st.size();
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/893
參考資料:
https://leetcode.com/problems/groups-of-special-equivalent-strings/
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)
