给出两个字符串,问其中一个字符串使用以下两种操作(次数不限),是否能转换为另一个
1. 交换两个字符
2. 把其中一个字符串中的所有a字符全部换成b,同时b字符全部同时换成a
总结下来只要判断
1. 两个字符串中出现的字符种类完全一致(用python的set实现)
2. 两个字符串中每个字符出现次数的count排序后完全一致(参考Discussion学到的python的Counter)
所以有以下两种写法(用两次Counter快很多):
1 #1657
2 #Runtime: 1271 ms
3 #Memory Usage: 15.3 MB
4
5 class Solution(object):
6 def closeStrings(self, word1, word2):
7 """
8 :type word1: str
9 :type word2: str
10 :rtype: bool
11 """
12 return sorted(Counter(word1).values()) == sorted(Counter(word2).values()) and set(word1) == set(word2)
1 #1657
2 #Runtime: 495 ms
3 #Memory Usage: 15.4 MB
4
5 class Solution(object):
6 def closeStrings(self, word1, word2):
7 """
8 :type word1: str
9 :type word2: str
10 :rtype: bool
11 """
12 return Counter(Counter(word1).values()) == Counter(Counter(word2).values()) and set(word1) == set(word2)