Technology Sharing

LeetCode 290. Word Patterns

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

LeetCode 290. Word Patterns

Given a pattern and a string s, determine whether s follows the same pattern.
The compliance here refers to a complete match, for example, there is a bidirectional corresponding rule between each letter in pattern and each non-empty word in string s.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = “aaaa”, s = “dog cat cat dog”
Output: false
hint:
1 <= pattern.length <= 300
pattern contains only lowercase English letters
1 <= s.length <= 3000
s contains only lowercase English letters and ' '
s does not contain any leading or trailing spaces
Each word in s is separated by a single space.

Hash table, bijective relation

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        length = len(pattern)
        sub_strs = s.split()
        if len(pattern) != len(sub_strs):
            return False
        d1, d2 = {}, {}
        for i in range(length):
            if pattern[i] in d1:
                if d1[pattern[i]] != sub_strs[i]:
                    return False
            if sub_strs[i] in d2:
                if d2[sub_strs[i]] != pattern[i]:
                    return False
            d1[pattern[i]] = sub_strs[i]
            d2[sub_strs[i]] = pattern[i]
        return True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17