forked from nyuhuyang/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
word-pattern.py
82 lines (73 loc) · 2.38 KB
/
word-pattern.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# Time: O(n)
# Space: O(c), c is unique count of pattern
# Given a pattern and a string str, find if str follows the same pattern.
#
# Examples:
# 1. pattern = "abba", str = "dog cat cat dog" should return true.
# 2. pattern = "abba", str = "dog cat cat fish" should return false.
# 3. pattern = "aaaa", str = "dog cat cat dog" should return false.
# 4. pattern = "abba", str = "dog dog dog dog" should return false.
#
# Notes:
# 1. Both pattern and str contains only lowercase alphabetical letters.
# 2. Both pattern and str do not have leading or trailing spaces.
# 3. Each word in str is separated by a single space.
# 4. Each letter in pattern must map to a word with length that is at least 1.
from itertools import izip # Generator version of zip.
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
if len(pattern) != self.wordCount(str):
return False
w2p, p2w = {}, {}
for p, w in izip(pattern, self.wordGenerator(str)):
if w not in w2p and p not in p2w:
# Build mapping. Space: O(c)
w2p[w] = p
p2w[p] = w
elif w not in w2p or w2p[w] != p:
# Contradict mapping.
return False
return True
def wordCount(self, str):
cnt = 1 if str else 0
for c in str:
if c == ' ':
cnt += 1
return cnt
# Generate a word at a time without saving all the words.
def wordGenerator(self, str):
w = ""
for c in str:
if c == ' ':
yield w
w = ""
else:
w += c
yield w
# Time: O(n)
# Space: O(n)
class Solution2(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
words = str.split() # Space: O(n)
if len(pattern) != len(words):
return False
w2p, p2w = {}, {}
for p, w in izip(pattern, words):
if w not in w2p and p not in p2w:
# Build mapping. Space: O(c)
w2p[w] = p
p2w[p] = w
elif w not in w2p or w2p[w] != p:
# Contradict mapping.
return False
return True