Given a pattern and a string str, findifSTR follows the same pattern. Here follow means a full match, such that there was a bijection between a letter in pattern and a non-empty word in Str. Examples:pattern= "ABBA", str = "Dog cat Cat Dog" shouldreturn true. Pattern= "ABBA", str = "Dog cat cat Fish" shouldreturn false. Pattern= "AAAA", str = "Dog cat Cat Dog" shouldreturn false. Pattern= "ABBA", str = "dog dog Dog" shouldreturn false. Notes:you assume pattern contains only lowercase letters, and STR contains lowercase letters separated by a single spa CE.
Note that this is a one by one mapping, that is, if the A->dog, B->dog, should return false, so should be on the basis of HashMap to add a layer of check, even if does not contain the key, before adding the map should check Map.values (). Contains (String)
1 Public classSolution {2 Public BooleanWordpattern (string pattern, string str) {3 if(pattern==NULL|| str==NULL)return false;4string[] all = Str.split ("");5 6 if(Pattern.length ()! = all.length)return false;7Hashmap<character, string> map =NewHashmap<character, string>();8 for(inti=0; I<pattern.length (); i++) {9 if(!Map.containskey (Pattern.charat (i))) {Ten if(Map.values (). Contains (All[i]))return false; One Map.put (Pattern.charat (i), all[i]); A } - Else { - if(!Map.get (Pattern.charat (i)). Equals (All[i] ) the return false; - } - } - return true; + } -}
Leetcode:word Pattern