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-emptyword 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.
Solution1:
思路:看起来很简单的一道题,用hashmap做就可以了。但是要注意几个cornercase,abba对应dog dog dog dog。要检查是不是
不同的字母存的string是否一样.
之前写的有点问题,用map的containsvalue来检查是不是对应。
public class Solution { public boolean wordPattern(String pattern, String str) { Map<Character,String> check=new HashMap<Character,String>(); String[] res=str.trim().split(" "); if(res.length!=pattern.length()) { return false; } for(int i=0;i<pattern.length();i++) { char current=pattern.charAt(i); if(!check.containsKey(current)) { if(check.containsValue(res[i])) { return false; } check.put(current,res[i]); } else { if(!check.get(current).equals(res[i])) { return false; } } } return true; } }