题目:
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.
题解:
通过建立HashMap 来存储 character 和 string 之间的对应来检查patter.
但这里要注意需要建立两个HashMap, 既要有character 到 string 的对应也要有string 到 character的对应。
e.g. "aaaa", str = "dog cat cat dog" should return false. 但是若是没有 char 到 string 的对应就会返回true.
pattern = "abba", str = "dog dog dog dog" should return false. 但是若是没有 string 到 char的对应就会返回true.
Note: Character 类 也有一个equals(), 和 String的相同,使用起来也相同。
Time Complexity: O(pattern.length()). Space: O(pattern.length()).
AC Java:
1 public classSolution {2 public booleanwordPattern(String pattern, String str) {3 if(pattern == null || pattern.length() == 0){4 return false;5 }6 if(str == null || str.length() == 0){7 return false;8 }9 String [] s = str.split("\\s+");10 if(pattern.length() !=s.length){11 return false;12 }13 //hm1 contains string -> character pair
14 HashMap hm1 = new HashMap();15 for(int i = 0; i string pair
25 HashMap hm2 = new HashMap();26 for(int i = 0; i