思路:用两个hash表来存储pattern中每个字母对应的word和单词中每个word对应的pattern中的字母。
def word_pattern(pattern, words): ‘‘‘ :param pattern: str :param words: str :return: boolean ‘‘‘ word_list = words.split() word_buffer = {} pattern_buffer = {} i = 0 if len(word_list) != len(pattern): return False for each in word_list: if each in word_buffer.keys(): if word_buffer.get(each) == pattern[i]: i += 1 continue else: return False else: if pattern[i] in pattern_buffer.keys(): return False else: word_buffer[each] = pattern[i] pattern_buffer[pattern[i]] = each i += 1 return True
以下是我在leetcode上提交的结果:
leetcode上的题目的地址是:https://leetcode.com/problems/word-pattern/description/
原文:https://www.cnblogs.com/whatyouknow123/p/9215723.html