放一起寫是因為這兩個問題很像,都是利用hashset解決的問題,不過用的時候才發現對python的hash還是不太熟,太多語法糖不會用了,這個問題只能慢慢看別人的Solutions解決了,沒啥好辦法。
- Isomorphic Strings
給定字符串s和t,輸出BOOL決定它們是否同構。同構是指的s可以通過字母替換變成t,替換的時候,兩個字母不能替換成同一個,但字母可以替換成和自身相同的字母(同時遵守前一條)。
先放自己的代碼,就是利用dict當hashmap:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
length = len(s)
usedCharIns = {}
usedCharInt = {}
for i in range(length):
if s[i] not in usedCharIns:
usedCharIns[s[i]] = t[i]
elif usedCharIns[s[i]] != t[i]:
return False
if t[i] not in usedCharInt:
usedCharInt[t[i]] = s[i]
elif usedCharInt[t[i]] != s[i]:
return False
return True
但是看Solutions里有巧的多的方法。。。。。。只用一行python
def isIsomorphic3(self, s, t):
return len(set(zip(s, t))) == len(set(s)) == len(set(t))
Word Pattern也是一樣的問題,只是把字符串t換成了用空格隔開的字符串
def wordPattern(self, pattern, str):
s = pattern
t = str.split()
return len(set(zip(s, t))) == len(set(s)) == len(set(t)) and len(s) == len(t)
結論是還要對python的語言特性多學習,什么map,set,zip,tuple,lambda之類的和其他語言不太一樣的地方。