[LeetCode] #290 单词规律

给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。

这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。

输入: pattern = "abba", str = "dog cat cat dog"

输出: true

类似题目[LeetCode] #205 同构字符串

使用两个HashMap表示相互的映射关系

class Solution {
    public boolean wordPattern(String pattern, String s) {
        String[] split = s.split(" ");
        if (split.length != pattern.length()) return false;
        HashMap<Character,String> map1 = new HashMap<>();
        String t1 = null,t2 = null;
        for(int i = 0; i < pattern.length(); i++){
            t1 = map1.put(pattern.charAt(i),split[i]);
            t2 = map1.get(pattern.charAt(i));
            if(t1 != null && !t1.equals(t2)) return false;
        }
        HashMap<String,Character> map2 = new HashMap<>();
        Character s1 = null,s2 = null;
        for(int i = 0; i < pattern.length(); i++){
            s1 = map2.put(split[i],pattern.charAt(i));
            s2 = map2.get(split[i]);
            if(s1 != null && !s1.equals(s2)) return false;
        }
        return true;
    }
}

使用一个HashMap,利用下标i作为映射的中间联系

class Solution {
    public boolean wordPattern(String pattern, String str) {
        String[] words = str.split(" ");
        if (words.length != pattern.length()) return false;
        Map<Object, Integer> map = new HashMap<>();
        for (Integer i = 0; i < words.length; i++) 
            if (map.put(pattern.charAt(i), i) != map.put(words[i], i)) return false;
        return true;
    }
}

知识点:

总结:

posted @ 2021-09-16 13:43  1243741754  阅读(28)  评论(0编辑  收藏  举报