Given a pattern
and a string str
, find if str
follows the same pattern.
Here follow means a full match, such that there was a bijection between a letter in and pattern
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:
Assume contains only pattern
lowercase letters, and contains lowercase letters separated by str
a single space.
Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
1 Public classSolution {2 Public BooleanWordpattern (string pattern, string str) {3Hashmap<character, string> HM =NewHashmap<character, string>();4Set<string> set =NewHashset<string>();5string[] arr = Str.split ("");6 if(Arr.length! = Pattern.length ())return false;7 for(intI =0;i< pattern.length (); i++){8 if(Hm.get (Pattern.charat (i))! =NULL){9 if(!hm.get (Pattern.charat (i)). Equals (Arr[i]))return false;Ten}Else{ One if(Set.contains (Arr[i]))return false; A Else{ - Hm.put (Pattern.charat (i), arr[i]); - Set.add (Arr[i]); the } - } - } - return true; + - } +}
290. Word Pattern Java Solutions