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
.
Examples:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"abba"
, str ="dog dog dog dog"
should return false.
Difficulty: Easy
Solution: HashMap
public class Solution {
public boolean wordPattern(String pattern, String str) {
HashMap<String, Character> map = new HashMap<String, Character>();
int index = 0, i = 0;
for(i = 0; i < pattern.length(); i++){
int start = index;
if(index == str.length())
break;
while(index < str.length() && str.charAt(index) != ' '){
index++;
}
String temp = str.substring(start, index);
if(!map.containsKey(temp)){
if(map.containsValue(pattern.charAt(i)))
return false;
map.put(temp, pattern.charAt(i));
}
else{
if(map.get(temp) != pattern.charAt(i)){
return false;
}
}
if(index < str.length() && str.charAt(index) == ' ')
index++;
}
if(i != pattern.length() || index!=str.length())
return false;
return true;
}
}