题目描述:
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》 key保存pattern中的字符,value保存words中的字符串,
比较相同key值的value是否相同
public boolean wordPattern(String pattern , String str){
HashMap<Character,String> map = new HashMap<Character,String>();
String[] words = str.split(" ");
if(words.length!=pattern.length())
return false;
for(int i =0 ; i<words.length;i++){
if(!map.containsKey(pattern.charAt(i))){
if(map.containsValue(words[i]))
return false;
map.put(pattern.charAt(i), words[i]);
}else if(!map.get(pattern.charAt(i)).equals(words[i])){
return false;
}
}
return true;
}
第二种方案:
利用hashMap put方法返回值的特性,比较pattern 和word对应的下标是否一致
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map map = new HashMap();
for (Integer i=0; i<words.length; ++i)
if (map.put(pattern.charAt(i), i) != map.put(words[i], i))
return false;
return true;
}