您的位置:首页 > 其它

word pattern

2016-07-05 08:24 218 查看
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保存住一一对应关系,然后每次循环检测是否对应即可。否则return false

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        if(pattern == null && str == null) return true;
        if(pattern == null || str == null) return false;
        
        String[] strs = str.split(" ");
        if(strs.length != pattern.length()) return false;
        HashMap<Character, String> ptos = new HashMap<Character, String>();
        HashMap<String, Character> stop = new HashMap<String, Character>();
        for(int i=0; i<strs.length; i++){
            char c = pattern.charAt(i);
            if(ptos.containsKey(c)){
                if(!ptos.get(c).equals(strs[i])){
                    return false;
                }
            } else {
                ptos.put(c, strs[i]);
            }
            
            if(stop.containsKey(strs[i])){
                if(stop.get(strs[i]) != c){
                    return false;
                }
            } else {
                stop.put(strs[i],c);
            }
        }
        return true;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: