一 读懂题目
二. 分析,推导解法,产生思路。
解题思路:双射;两张哈希表
三 代码实现
def isIsomorphic1(self, s, t):
'''
双射;两张哈希表
'''
dic_s = {}
dic_t = {}
i = 0
while i < len(s):
if s[i] not in dic_s and t[i] not in dic_t : # 两张哈希表各自都是第一次出现
dic_s[s[i]] = t[i]
dic_t[t[i]] = s[i]
elif s[i] in dic_s and t[i] in dic_t :
if dic_s[s[i]] != t[i] :
return False
else:
return False
i += 1
return True
类型题:290 单词规律
一 读懂题目:
二 思路:同样是双射问题,只是是字母对应字符串
三 代码实现:
def wordPattern(self, pattern, s):
"""
:type pattern: str
:type s: str
:rtype: bool
"""
# 找规律
dic_p = {}
dic_s = {}
i = 0
j = 0
s_start = 0
while i < len(pattern):
# 找到s中的字符串,再比较。手写空格划分
while j < len(s) and s[j] != ' ': # 找到第一个空格
j += 1
s_substr = s[s_start:j] # 根据s_start与其后的第一个空格,获取字符串
j += 1 # 调整j与s_start的位置
s_start = j
if pattern[i] not in dic_p and s_substr not in dic_s: # 两张哈希表各自都是第一次出现
dic_p[pattern[i]] = s_substr
dic_s[s_substr] = pattern[i]
elif pattern[i] in dic_p and s_substr in dic_s: # 只有一种情况才是满足条件的dic_s[s[i]] == t[i]
if dic_p[pattern[i]] != s_substr:
return False
else:
return False
i += 1
if i == len(pattern) and j != len(s)+1: # 特殊情况(长度不对应):aaa对应aa aa aa aa
return False
return True
def wordPattern2(self, pattern, s):
# 官方标准答案
word2ch = dict()
ch2word = dict()
words = s.split() # 根据空格划分字符串
if len(pattern) != len(words): # 长度不对应直接返回false
return False
for ch, word in zip(pattern, words):
if (word in word2ch and word2ch[word] != ch) or (ch in ch2word and ch2word[ch] != word):
return False
word2ch[word] = ch
ch2word[ch] = word
return True