zoukankan      html  css  js  c++  java
  • 单词规律

    单词规律

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

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

    示例1:

    输入: pattern = "abba", str = "dog cat cat dog"
    输出: true
    示例 2:

    输入:pattern = "abba", str = "dog cat cat fish"
    输出: false
    示例 3:

    输入: pattern = "aaaa", str = "dog cat cat dog"
    输出: false
    示例 4:

    输入: pattern = "abba", str = "dog dog dog dog"
    输出: false

    解题思路:用两个哈希表来分别保存字符和对应的字符串,以及字符和对应的下标,之后进行比对即可

    class Solution {
        public boolean wordPattern(String pattern, String s) {
            String strs[] = s.split(" ");
            char ch[] = pattern.toCharArray();
        
            if(strs.length != ch.length)
                return false;
            
            Map<String, Character> map1 = new HashMap();
            Map<Character, Integer> map2 = new HashMap();
            
            for(int i = 0; i < ch.length; i++) {
                map1.put(strs[i], map1.getOrDefault(strs[i], ch[i]));
                map2.put(ch[i], map2.getOrDefault(ch[i], i));
            }
            
            for(int i = 0; i < ch.length; i++) {
                char c = map1.get(strs[i]);
                int idx = map2.get(ch[i]);
                if(c != ch[i]) {
                    return false;
                } else if(!strs[idx].equals(strs[i])) {
                    return false;
                }
            }
            
            return true;
        }
    }
    
  • 相关阅读:
    nginx 的请求处理阶段
    docker 的实践操作
    inno setup 1
    缓存算法
    think in uml-关系
    centos mono
    think in uml 2.1
    TFS 创建分支
    think in uml 1
    WebCast课程列表2
  • 原文地址:https://www.cnblogs.com/katoMegumi/p/14142210.html
Copyright © 2011-2022 走看看