Word Pattern
Sergei Golitsynhttps://leetcode.com/problems/word-pattern/
Given a pattern and a string s, find if s 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 s.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog" Output: true
Example 2:
Input: pattern = "abba", s = "dog cat cat fish" Output: false
Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog" Output: false
Solution:
Ok, ok, looks like that is an easy problem. Right?
But a want to add some additional cases:
aabba bbaac
And return will be false. is it clear?
We should have links between both sides, like a to b and b to a, because it is possible to have an opposite case.
That is why we have to prepare two dictionaries and fill them. And if we successfully iterate over the word/sentence, that is it. =)
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
Map<Character, String> mapPat = new HashMap<>();
Map<String, Character> sMap = new HashMap<>();
if (pattern.length() != words.length){
return false;
}
for(int i = 0; i < words.length; i++){
char curChar = pattern.charAt(i);
String curWord = words[i];
if (mapPat.containsKey(curChar)){
if(!mapPat.get(curChar).equals(curWord)){
return false;
}
} else if (sMap.containsKey(curWord)){
if(!sMap.get(curWord).equals(curChar)){
return false;
}
}
else {
mapPat.put(curChar, curWord);
sMap.put(curWord, curChar);
}
}
return true;
}