Own Code:
- create dictionary which counts the occurrence of every characters.
- Check if there is a character where another dictionary don't have
- sort the values and check if all the values are same
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
if len(word1) != len(word2): return False
dict_word1, dict_word2 = {}, {}
for item in word1:
dict_word1[item] = dict_word1.get(item, 0) + 1
for item in word2:
dict_word2[item] = dict_word2.get(item, 0) + 1
if not dict_word1.get(item):
return False
values_word1 = sorted(list(dict_word1.values()))
values_word2 = sorted(list(dict_word2.values()))
index = 0
while index < len(values_word1):
if values_word1[index] != values_word2[index]:
return False
index += 1
return True
Better Code:
那么我们可以手动统计每个字符出现的次数,并比较它们的频次集合是否相同。同时,我们还需要比较两个单词的字符集合是否相同。
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
# 统计字符频次
freq1 = {}
freq2 = {}
for char in word1:
freq1[char] = freq1.get(char, 0) + 1
for char in word2:
freq2[char] = freq2.get(char, 0) + 1
# 检查字符集合是否相同
if set(freq1.keys()) != set(freq2.keys()):
return False
# 检查频次列表是否相同
return sorted(freq1.values()) == sorted(freq2.values())
If you use Counter
, running time will decrease, but the main idea is same.
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
counter_word1 = Counter(word1)
counter_word2 = Counter(word2)
return counter_word1.keys() == counter_word2.keys() and sorted(counter_word1.values()) == sorted(counter_word2.values())