Use two hash maps for bi-directional mapping between pattern characters and words in s.
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
if len(pattern) != len(words):
return False
char_to_word = {}
word_to_char = {}
for char, word in zip(pattern, words):
if char in char_to_word and char_to_word[char] != word:
return False
if word in word_to_char and word_to_char[word] != char:
return False
char_to_word[char] = word
word_to_char[word] = char
return True
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (words.length != pattern.length()) {
return false;
}
Map charToWord = new HashMap<>();
Map wordToChar = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String w = words[i];
if (charToWord.containsKey(c) && !charToWord.get(c).equals(w)) {
return false;
}
if (wordToChar.containsKey(w) && wordToChar.get(w) != c) {
return false;
}
charToWord.put(c, w);
wordToChar.put(w, c);
}
return true;
}
}