LeetCode290.单词规律

简单的题我简单的hash~

class Solution {
    public boolean wordPattern(String pattern, String s) {
        if(pattern == null || s == null) return false;
        String[] t = s.split(" ");//拆分字符串s
        if(t.length != pattern.length()) return false;
        Map<Character,String> map = new HashMap<>();//用HashMap存放字母和单词的映射
        for(int i = 0; i < pattern.length(); i++){
            char temp = pattern.charAt(i);
            if(map.containsKey(temp)){ 
                if(!map.get(temp).equals(t[i])){
                    return false;
                }
            } else {
                if(map.containsValue(t[i])){
                    return false;
                } else {
                    map.put(temp,t[i]);
                } 
            }
        }
        return true;
    }
}

你可能感兴趣的:(LeetCode)