我正在尝试制作一个程序,比较word1字符串与word2字符串只发生一次
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
word1 = [x.strip() for x in word1]
word2 = [x.strip() for x in word2]
update = False
for x in word1:
if(x in word2):
update = True
if(type(x) is str):
a = word1.index(x)
b = word2.index(x)
word1[a]=''
word2[b]=''
else:
update = False
else:
update = False
break
return update
print(Solution.closeStrings(Solution,word1='a',word2='aa'))
输入
word1 = 'a',word2 ='aa'
预期Output = False
实际Output = True
-
print(Solution.closeStrings(Solution,word1='a',word2='aa'))
创建一个类是为了能够创建它的实例。这样,您就不需要将
Solution
作为self
参数传递。 -
word1 = [x.strip() for x in word1]
看起来你想要删除空格。但是你会得到一个字符串列表,其中的空格为空字符串。那不是你想要的。查看
的输出
print([x.strip() for x in "Hello world"])
-
你的算法太复杂了。
您可以简单地计算word2:
中每个字符的出现次数。
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
for x in word1:
if word2.count(x) != word1.count(x): return False
return True
s = Solution()
print(s.closeStrings(word1='a',word2='aa'))
print(s.closeStrings(word1='abcb',word2='bcab'))
扩展到其他更多的解决方案的答案@Thomas Weller很好地解释了他
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
for i in word1:
if i not in word2:
return False
for i in word2:
if i not in word1:
return False
return True
def closeStrings2(self, word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
if set(word1) != set(word2):
return False
return True
def closeStrings3(self, word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
if sorted(word1) != sorted(word2):
return False
return True
print(Solution().closeStrings(word1="cabbba", word2="abbccc"))
print(Solution().closeStrings3(word1="cabbba", word2="aabbss"))
print(Solution().closeStrings3(word1="cabbba", word2="aabbss"))