LeetCode: 290. Word Pattern
题目描述
Given a pattern
and a string str
, find if str
follows the same pattern
.
Here follow means a full match, such that there is a bijection between a letter in pattern
and a non-empty word in str
.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", str = "dog dog dog dog"
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.
解题思路 —— 哈希
由于 pattern
是小写字母组成,因此可以用 pattern[i] - 'a'
来映射 pattern[i]
。
因此就可以用 var wordsMap [26]string
数组来存放 pattern
和 str
中的单词的映射关系。
AC 代码
func wordPattern(pattern string, str string) bool {
words := strings.Split(str, " ")
var wordsMap [26]string
if len(pattern) != len(words) {
return false
}
for i := 0; i < len(words); i++{
if wordsMap[pattern[i]-'a'] == "" {
for j := 0; j < len(wordsMap); j++{
if wordsMap[j] == words[i] {
return false
}
}
wordsMap[pattern[i]-'a'] = words[i]
} else if wordsMap[pattern[i]-'a'] != words[i] {
return false
}
}
return true
}