290. Word Pattern
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 class Solution {
public boolean wordPattern(String pattern, String str) {
HashMap<Character,String> map = new HashMap<Character,String>();
String[] arr = str.split(" ");
if(arr.length!=pattern.length()) return false;
for(int i = 0; i< pattern.length(); i++){
char a = pattern.charAt(i);
String b = arr[i];
if(map.containsKey(a)){
if(map.get(a).equals(b)){
continue;
}
return false;
}else{
if(map.containsValue(b)){
return false;
}else{
map.put(a,b);
}
}
}
return true;
}
}
其中的如何将字符串分离出来,耽误了较长时间,将字符串按空格分离而后,保存成数组格式。
可以使用split 搞定,这个方法挺厉害的;(哥哥最近有点郁闷,脑袋疼)