題目在這
不需要使用兩個哈希表就可以實現(xiàn),具體思路是使用pattern中的值作為key,使用str中的值作為value,然后進(jìn)行判斷處理
swift實現(xiàn)
//: Playground - noun: a place where people can play
func WordPattern(_ pattern : String, _ str : String) -> Bool{
let strArr = str.split(separator: " ")
var dic = [Character : String]()
if strArr.count != pattern.characters.count || Set(strArr).count != Set(pattern.characters).count{//"abba","mu mu mu mu"
return false
}
for (i,v) in pattern.characters.enumerated(){
if dic[v] == nil{
dic[v] = String(strArr[i])
}else{
if dic[v] != String(strArr[i]) {
return false
}
}
}
return true
}
WordPattern("aass", "mu mu dy dy")
python實現(xiàn)
#-*- coding:utf-8 -*-
#@Filename:leetcode290
#@Date:2018-09-10 20:44
#@auther:Mudy
#@E-mail:2808050775@qq.com
#@Blog:txmudy.cn
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
dic = {}
strArr = str.split(" ")
if len(strArr) != len(pattern) or len(set(strArr)) != len(set(pattern)):# "abba","mu mu mu mu"
return False
for i, v in enumerate(pattern):
if v not in dic:
dic[v] = strArr[i]
else:
if dic[v] != strArr[i] :
print(dic[v],strArr[i],end="\n")
return False
return True
if __name__ == "__main__":
s = Solution()
print(s.wordPattern("aabb","mudy mudy mudy mudy"))