leetcode No.290 单词模式(HashMap)

class Solution {
    public boolean wordPattern(String pattern, String str) {
        int len=pattern.length();
        String[] s=str.split(" ");//这里不要写成"" 里面要有空格
        if(len!=s.length) return false;
        HashMap<Character,String>map=new HashMap<>();
       // for(char c:pattern.toCharArray()){  不能用这行代码 因为要用到两次数组索引
        for(int i=0;i<len;++i){
            char c=pattern.charAt(i);
            if(map.containsKey(c)){
                if(!map.get(c).equals(s[i]))
                    return false;
            }
            else {
                if(map.values().contains(s[i]))
                    return false;
                else map.put(c,s[i]);
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33399567/article/details/89198690
今日推荐