zoukankan      html  css  js  c++  java
  • [LeetCode] Word Pattern

    Word Pattern

    Total Accepted: 4627 Total Submissions: 17361 Difficulty: Easy

    Given a pattern and a string str, find if str follows the same pattern.

    Examples:

    1. pattern = "abba", str = "dog cat cat dog" should return true.
    2. pattern = "abba", str = "dog cat cat fish" should return false.
    3. pattern = "aaaa", str = "dog cat cat dog" should return false.
    4. pattern = "abba", str = "dog dog dog dog" should return false.

    Notes:

    1. patterncontains only lowercase alphabetical letters, and str contains words separated by a single space. Each word in str contains only lowercase alphabetical letters.
    2. Both pattern and str do not have leading or trailing spaces.
    3. Each letter in pattern must map to a word with length that is at least 1.

    Credits:
    Special thanks to @minglotus6 for adding this problem and creating all test cases.

    /**
     * @param {string} pattern
     * @param {string} str
     * @return {boolean}
     */
    var wordPattern = function(pattern, str) {
        var s_to_p = {};
        var p_to_s = {};
        var pi = 0;
        var si = 0;
        if (!pattern || !str) return false;
        while (pi < pattern.length) {
            if (si >= str.length) return false;
            var word = "";
            var pt = pattern[pi];
            while (si < str.length && str[si] != " ") {
                word += str[si];
                si++;
            }
            si++;
            if (!s_to_p[word]) {
                s_to_p[word] = pattern[pi];
            }
            else {
                if (s_to_p[word] != pattern[pi]) return false;
            }
            
            if (!p_to_s[pt]) {
                p_to_s[pt] = word;
            }
            else {
                if (p_to_s[pt] != word) return false;
            }
            pi++;
        }
        if (si < str.length) return false;
        return true;
    };

    最简单的方法利用两个哈希表做双向的对应,主要容易错的是在各种edge cases,比如pattern 和 str 长度不对应,为空等。

     
     
  • 相关阅读:
    题解【luogu1073 最优贸易】
    题解【luogu4145 上帝造题的七分钟2(花神游历各国)】
    题解【bzoj2427 [HAOI2010]软件安装】
    以后会经常用cnblogs啦!
    题解【luogu4168 [Violet]蒲公英】
    题解【bzoj1010 [HNOI2008]玩具装箱TOY】
    题解【bzoj4653 [NOI2016] 区间】
    animation渐进实现点点点等待效果
    纯css loading动效
    文字和背景渐变动效
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4864400.html
Copyright © 2011-2022 走看看