[LeetCode] 290. Word Pattern 单词模式
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
.
Example 1:
Input: pattern ="abba"
, str ="dog cat cat dog"
Output: true
Example 2:
Input:pattern ="abba"
, str ="dog cat cat fish"
Output: false
Example 3:
Input: pattern ="aaaa"
, str ="dog cat cat dog"
Output: false
Example 4:
Input: pattern ="abba"
, str ="dog dog dog dog"
Output: false
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space.
给一个模式字符串,又给了一个单词字符串,判断单词字符串中单词出现的规律是否符合模式字符串中的规律。
解法1:哈希表。
解法2: 这个问题相当于同构字符串 205. Isomorphic Strings.
Java:
public boolean wordPattern(String pattern, String str) { String[] words = str.split(" "); if (words.length != pattern.length()) return false; Map index = new HashMap(); for (Integer i=0; i<words.length; ++i) if (index.put(pattern.charAt(i), i) != index.put(words[i], i)) return false; return true; }
Java:
public class Solution { public boolean wordPattern(String pattern, String str) { String[] words = str.split(" "); if (words.length != pattern.length()) return false; Map<Character, String> ps = new HashMap<>(); Map<String, Character> sp = new HashMap<>(); for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); String word = words[i]; if (!ps.containsKey(c)) ps.put(c, word); else if (!ps.get(c).equals(word)) return false; if (!sp.containsKey(word)) sp.put(word, c); else if (sp.get(word) != c) return false; } return true; } }
Java:
public boolean wordPattern(String pattern, String str) { String [] strArr = str.split(" "); LinkedHashMap<String, ArrayList<Integer>> map = new LinkedHashMap<String, ArrayList<Integer>>(); LinkedHashMap<String, ArrayList<Integer>> map2 = new LinkedHashMap<String, ArrayList<Integer>>(); for(int i=0; i<pattern.length(); i++){ map.putIfAbsent(pattern.charAt(i)+"", new ArrayList<Integer>()); map.get(pattern.charAt(i)+"").add(i); } for(int i=0; i<strArr.length; i++){ map2.putIfAbsent(strArr[i], new ArrayList<Integer>()); map2.get(strArr[i]).add(i); } return new ArrayList(map.values()).equals(new ArrayList(map2.values())); }
Java:
public class Solution { public boolean wordPattern(String pattern, String str) { String[] arr= str.split(" "); HashMap<Character, String> map = new HashMap<Character, String>(); if(arr.length!= pattern.length()) return false; for(int i=0; i<arr.length; i++){ char c = pattern.charAt(i); if(map.containsKey(c)){ if(!map.get(c).equals(arr[i])) return false; }else{ if(map.containsValue(arr[i])) return false; map.put(c, arr[i]); } } return true; } }
Python:
# 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
Python: wo
class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ s = str.split() if len(s) != len(pattern): return False m1 = {} m2 = {} for i in xrange(len(s)): if m1.get(pattern[i]) != m2.get(s[i]): return False m1[pattern[i]] = i m2[s[i]] = i return True
Python:
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
Python:
def wordPattern1(self, pattern, str): s = pattern t = str.split() return map(s.find, s) == map(t.index, t) def wordPattern2(self, pattern, str): f = lambda s: map({}.setdefault, s, range(len(s))) return f(pattern) == f(str.split()) def wordPattern3(self, pattern, str): s = pattern t = str.split() return len(set(zip(s, t))) == len(set(s)) == len(set(t)) and len(s) == len(t)
Python:
class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ x = str.split(' ') lsp = len(set(pattern)) lsx = len(set(x)) return len(x)==len(pattern) and lsx==lsp and lsp== len(set(zip(pattern, x)))
C++:
bool wordPattern(string pattern, string str) { map<char, int> p2i; map<string, int> w2i; istringstream in(str); int i = 0, n = pattern.size(); for (string word; in >> word; ++i) { if (i == n || p2i[pattern[i]] != w2i[word]) return false; p2i[pattern[i]] = w2i[word] = i + 1; } return i == n; }
C++:
class Solution { public: bool wordPattern(string pattern, string str) { unordered_map<char, int> m1; unordered_map<string, int> m2; istringstream in(str); int i = 0; for (string word; in >> word; ++i) { if (m1.find(pattern[i]) != m1.end() || m2.find(word) != m2.end()) { if (m1[pattern[i]] != m2[word]) return false; } else { m1[pattern[i]] = m2[word] = i + 1; } } return i == pattern.size(); } };
类似题目:
[LeetCode] 205. Isomorphic Strings 同构字符串[LeetCode] 291. Word Pattern II 词语模式 II
All LeetCode Questions List 题目汇总