题目在这
不需要使用两个哈希表就可以实现,具体思路是使用pattern中的值作为key,使用str中的值作为value,然后进行判断处理
swift实现
//: 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实现
#-*- 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"))