Word Pattern
Given apattern
and a stringstr
, find ifstr
follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter inpattern
and a non-empty word instr
.
Examples:
pattern =
"abba"
, str ="dog cat cat dog"
should return true.
pattern =
"abba"
, str ="dog cat cat fish"
should return false.
pattern =
"aaaa"
, str ="dog cat cat dog"
should return false.
pattern =
"abba"
, str ="dog dog dog dog"
should return false.
Notes:
You may assumepattern
contains only lowercase letters, andstr
contains lowercase letters separated by a single space.
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
if not pattern and not str:
return True
# since str has words separated by spaces
str_arr = str.split()
if len(str_arr) != len(pattern):
return False
dict = {}
start = 0
for idx in xrange(len(pattern)):
ch = pattern[idx]
substr = ''
#/////////////////////////////////////////
# easy to obtain substr when the str has ' ' (space) separating words
#/////////////////////////////////////////
for idx2 in xrange(start, len(str)):
if str[idx2] != ' ':
substr += str[idx2]
else:
start = idx2 + 1
break;
#print 'ch: ', ch, ' substr: ', substr, ' start: ', start
if ch not in dict:
if substr not in dict.values():
#print 'hashing: ', ch, ' -> ', substr
dict[ch] = substr
else:
return False
else:
if dict[ch] != substr:
return False
return True
Last updated
Was this helpful?