Does a String Match a Bijection Pattern
Problem
Given a pattern like "abba" and a sentence like "dog cat cat dog", decide whether there is a bijection between pattern letters and words such that the pattern, applied letter by letter, reproduces the sentence. Walk pattern letters and words in lockstep, with maps in both directions; reject as soon as either map disagrees with what's already recorded.
Input
pattern = "abba", s = "dog cat cat dog"Output
truea ↔ dog, b ↔ cat is consistent.
def word_pattern(pattern, s):
words = s.split(" ")
if len(words) != len(pattern):
return False
c_to_w, w_to_c = {}, {}
for c, w in zip(pattern, words):
if c in c_to_w and c_to_w[c] != w:
return False
if w in w_to_c and w_to_c[w] != c:
return False
c_to_w[c] = w
w_to_c[w] = c
return True
function wordPattern(pattern, s) {
const words = s.split(" ");
if (words.length !== pattern.length) return false;
const cToW = new Map(), wToC = new Map();
for (let i = 0; i < pattern.length; i++) {
const c = pattern[i], w = words[i];
if (cToW.has(c) && cToW.get(c) !== w) return false;
if (wToC.has(w) && wToC.get(w) !== c) return false;
cToW.set(c, w);
wToC.set(w, c);
}
return true;
}
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (words.length != pattern.length()) return false;
Map<Character, String> cToW = new HashMap<>();
Map<String, Character> wToC = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String w = words[i];
if (cToW.containsKey(c) && !cToW.get(c).equals(w)) return false;
if (wToC.containsKey(w) && wToC.get(w) != c) return false;
cToW.put(c, w);
wToC.put(w, c);
}
return true;
}
}
bool wordPattern(string pattern, string s) {
vector<string> words;
string w;
stringstream ss(s);
while (ss >> w) words.push_back(w);
if (words.size() != pattern.size()) return false;
unordered_map<char, string> cToW;
unordered_map<string, char> wToC;
for (size_t i = 0; i < pattern.size(); ++i) {
char c = pattern[i];
const string& ww = words[i];
if (cToW.count(c) && cToW[c] != ww) return false;
if (wToC.count(ww) && wToC[ww] != c) return false;
cToW[c] = ww;
wToC[ww] = c;
}
return true;
}