Leetcode - Isomorphic Strings
Leetcode - Binary Tree Maximum Path Sum

Leetcode - Word Pattern

violet posted @ Apr 29, 2020 08:20:53 AM in 算法 with tags Algorithm Golang hash , 211 阅读

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
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter