290. Word Pattern
Problem
Decide whether the words of s follow pattern: there must be a one-to-one mapping between pattern letters and words, so equal letters correspond to equal words and different letters to different words.
Example: pattern = "abba", s = "dog cat cat dog" → true; s = "dog cat cat fish" → false
Same idea as Isomorphic Strings: the mapping letter ↔ word must be a bijection, so keep both directions and reject any conflict. Also reject different lengths.
Complexity: O(n).
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
if len(words) != len(pattern):
return False
p2w, w2p = {}, {}
for p, w in zip(pattern, words):
if p2w.setdefault(p, w) != w or w2p.setdefault(w, p) != p:
return False
return True
assert Solution().wordPattern("abba", "dog cat cat dog") is True
assert Solution().wordPattern("abba", "dog cat cat fish") is False
assert Solution().wordPattern("aaaa", "dog cat cat dog") is False
assert Solution().wordPattern("abba", "dog dog dog dog") is False
assert Solution().wordPattern("aaa", "aa aa aa aa") is False
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (words.length != pattern.length()) return false;
Map<Character, String> p2w = new HashMap<>();
Map<String, Character> w2p = new HashMap<>();
for (int i = 0; i < words.length; i++) {
char p = pattern.charAt(i);
String w = words[i];
if (!p2w.computeIfAbsent(p, x -> w).equals(w)) return false;
if (w2p.computeIfAbsent(w, x -> p).charValue() != p) return false;
}
return true;
}
}
func wordPattern(pattern string, s string) bool {
words := strings.Fields(s)
if len(words) != len(pattern) {
return false
}
p2w, w2p := map[byte]string{}, map[string]byte{}
for i, w := range words {
p := pattern[i]
if x, ok := p2w[p]; ok && x != w {
return false
}
if x, ok := w2p[w]; ok && x != p {
return false
}
p2w[p], w2p[w] = w, p
}
return true
}