LeetCode-Python-893. Groups of Special-Equivalent Strings
-
題目理解
-
程式設計方法
一.題目理解
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
Return the number of groups of special-equivalent strings from A
題目中提到的轉換(move)指的是交換n次偶數次位置或者奇數次位置的字元。如果字串A可以通過move轉換為字串B,即認為兩者是special-equivalent strings。
題目中提到字串都由小寫字母組成,且字串陣列中字串的長度是一致的。
要求尋找特殊等價字串的個數。
字串中一共包括26個小寫字母,即可建立一個序列(KEY)統計個數。序列可以由偶數次位置與奇數次位置的順序組成。
二.程式設計方法
Python 中字典是一種可儲存任何型別物件的容器,值可以取任何資料型別,但鍵必須是不可變的,如字串,數字或元組。
sameWord={}
for i in A:
if len(i)>=2:
key=(tuple(sorted(i[1::2])),tuple(sorted(i[0::2]))) //建立序列key
else:
key=i //字串為單字母時自身滿足等價
sameWord[key]=sameWord.get(key,0)+1 //計數
print(len(sameWord))
上述即為利用字典資料結構來統計個數,Key為等價字串,值為個數。
題目要求只統計個數,不要具體等價字串的值。由此可以利用另一個數據結構Set,是一個無序不重複元素集, 基本功能包括關係測試和消除重複元素。所以直接將各自排序好的偶奇次拼接為字串放入set中,最後輸出set的長度即為等價字串的個數。
sameWord2=set()
for i in A:
sameWord2.add("".join(sorted(i[0::2]))+"".join(sorted(i[1::2])))
print(len(sameWord2))