Leetcode - Word Pattern
https://leetcode.com/problems/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
func wordPattern(pattern string, str string) bool { strs := strings.Split(str, " ") if len(pattern) != len(strs) { return false } hash1 := map[byte]string{} hash2 := map[string]byte{} for i := 0; i < len(strs); i++ { p := pattern[i] s := strs[i] if _, ok := hash1[p]; !ok { hash1[p] = s } if _, ok := hash2[s]; !ok { hash2[s] = p } if hash1[p] != s || hash2[s] != p { return false } } return true }