【LeetCode】290.单词规律(双映射)

题目链接

290. 单词规律

题目描述

解题思路

双哈希表

需要处理两个映射关系:pattern -> str,以及str -> pattern

如果只考虑pattern -> str的映射关系,则pattern = "abba"str = "dog dog dog dog"示例不通过。所以必须也得考虑str -> pattern的映射关系,双映射,双哈希。

AC代码

class Solution {
    public boolean wordPattern(String pattern, String s) {
        String sBuff[] = s.split(" ");
        Map<Character,String> p2s = new HashMap<>();
        Map<String,Character> s2p = new HashMap<>();
        if(pattern.length() != sBuff.length) return false;
        boolean flag1 = true;
        boolean flag2 = true;
        for(int i = 0; i < pattern.length(); i++){
            if(p2s.containsKey(pattern.charAt(i))){
                if(p2s.get(pattern.charAt(i)).equals(sBuff[i])==false){
                    flag1 = false;
                }
            }
            else p2s.put(pattern.charAt(i),sBuff[i]);
        }
        for(int i = 0; i < pattern.length(); i++){
            if(s2p.containsKey(sBuff[i])){
                if(s2p.get(sBuff[i]).equals(pattern.charAt(i))==false){
                    flag1 = false;
                }
            }
            else s2p.put(sBuff[i],pattern.charAt(i));
        }
        if(flag1 && flag2) return true;
        else return false;
    }
}
posted @ 2020-12-27 13:01  控球强迫症  阅读(109)  评论(0编辑  收藏  举报