[LeetCode]893. Groups of Special-Equivalent Strings
原題
You are given an arrayA
of strings.
Two stringsS
and T
are special-equivalent
if after any number of moves
, S == T.
Amove
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 fromA
.
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 A[i] A[i]
題解
明確題意
A。
然後,定義一個Special-Equivalent概念,如果有兩個字串S和T,將S串中的奇數位置相互移動若干次或不移動,偶數位置相互移動若干次或不移動之後,可以使兩個字串S和T相等,那麼稱為S和T是Special Equivalent。
思路
奇數位和偶數位是兩個分類,但是是一個緯度,如果解決了奇數位,那麼就解決了偶數位。
所以,先考慮偶數位。SE(even for string S)和TE(odd for string T)。判斷SE和TE能否通過調整各自內部字元的位置達到一致的問題,其實就是判斷SE和TE的組成元素是否一致,即排序後的字串是否一樣。同理,判斷奇數位的組成元素(字元)。
程式碼
class Solution { public: int numSpecialEquivGroups(vector<string>& A) { map<string, int> a; string es, os; for (auto str : A) { es = os = ""; for (int i = 0; i < str.length(); ++i) { if (i % 2 == 0) es += str[i]; if (i % 2 == 1) os += str[i]; } sort(es.begin(), es.end()); sort(os.begin(), os.end()); a[es + os] += 1; } return a.size(); } };
複雜度
M 代表陣列A的長度
N 代表A陣列中最長的字串的長度
時間複雜度:O(M*N*lgN)
原題:ofollow,noindex">https://leetcode.com/problems/groups-of-special-equivalent-strings/
文章來源:胡小旭 => [LeetCode]893. Groups of Special-Equivalent Strings