forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword_pattern.py
More file actions
47 lines (38 loc) · 1.22 KB
/
word_pattern.py
File metadata and controls
47 lines (38 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
Word Pattern
Given a pattern and a string, determine if the string follows the same
pattern via a bijection between pattern letters and words.
Reference: https://leetcode.com/problems/word-pattern/description/
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
def word_pattern(pattern: str, string: str) -> bool:
"""Check if a string follows the given pattern.
Args:
pattern: A pattern string of lowercase letters.
string: A space-separated string of words.
Returns:
True if the string follows the pattern, False otherwise.
Examples:
>>> word_pattern("abba", "dog cat cat dog")
True
>>> word_pattern("abba", "dog cat cat fish")
False
"""
mapping: dict[str, str] = {}
mapped_values: set[str] = set()
words = string.split()
if len(words) != len(pattern):
return False
for i in range(len(pattern)):
if pattern[i] not in mapping:
if words[i] in mapped_values:
return False
mapping[pattern[i]] = words[i]
mapped_values.add(words[i])
else:
if mapping[pattern[i]] != words[i]:
return False
return True