Leetcode[290] Word Pattern
05 Dec 2015###Task1 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.
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 assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
###Java
public class Solution {
public boolean wordPattern(String pattern, String str) {
if (pattern == null || str == null) {
return false;
}
String[] arr = str.split("\\s");
if (pattern.length() != arr.length) {
return false;
}
HashMap<String, Character> map = new HashMap<String, Character>();
for (int i = 0; i < arr.length; i++) {
if (map.containsValue(pattern.charAt(i)) && !map.containsKey(arr[i])) {
return false;
}
if (!map.containsKey(arr[i])) {
map.put(arr[i], pattern.charAt(i));
} else {
char cur = map.get(arr[i]);
if (cur != pattern.charAt(i)) {
return false;
}
}
}
return true;
}
}
###Python
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
map = {}
words = str.split(" ")
if len(pattern) != len(words):
return False
for i in range(len(pattern)):
if pattern[i] not in map.keys() and words[i] not in map.values():
map[pattern[i]] = words[i]
elif pattern[i] in map.keys() and map[pattern[i]] == words[i]:
continue
else:
return False
return True
###Points
- Python Split: str.split(‘ ‘) or use re: new_str = re.split(r’\s+’, str)