Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created May 11, 2016 18:49
Show Gist options
  • Save cangoal/5995b00d66a0e3432fadc64068eef08e to your computer and use it in GitHub Desktop.
Save cangoal/5995b00d66a0e3432fadc64068eef08e to your computer and use it in GitHub Desktop.
LeetCode - Word Patttern
// 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.
// Notes:
// You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
public boolean wordPattern(String pattern, String str) {
if(pattern == null || pattern.length() == 0) return pattern.equals(str);
String[] strCollection = str.split(" ");
if(strCollection.length != pattern.length()) return false;
HashMap<Character, String> map = new HashMap<Character, String>();
for(int i=0; i<pattern.length(); i++){
char c = pattern.charAt(i);
if(map.containsKey(c)){
if(!map.get(c).equals(strCollection[i])) return false;
} else{
if(map.containsValue(strCollection[i])) return false;
map.put(c, strCollection[i]);
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment