LeetCode 290. Word Pattern

題目

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

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples: pattern = "abba", str = "dog cat cat dog" should return true. pattern = "abba", str = "dog cat cat fish" should return false. pattern = "aaaa", str = "dog cat cat dog" should return false. pattern = "abba", str = "dog dog dog dog" should return false. Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

翻譯

給一個樣版跟一個字串,判斷字串是否有遵循樣版的格式。

這邊的遵循是說字串中的每一個詞都與樣版有一致的對應。

範例:
pattern = "abba", str = "dog cat cat dog" should return true. pattern = "abba", str = "dog cat cat fish" should return false. pattern = "aaaa", str = "dog cat cat dog" should return false. pattern = "abba", str = "dog dog dog dog" should return false.

可以假設樣版中只有小寫字母,字串中毎個詞用空白隔開。

思路

  1. 這跟205. Isomorphic Strings可以說是95%以上的像
  2. 一樣用map儲存出現過的樣版與字串的對應關係,當發現對應不成立,就回傳false

解題

/**
 * @param {string} pattern
 * @param {string} str
 * @return {boolean}
 */
var wordPattern = function(pattern, str) {
    var patternMap = {};
    var strMap = {};
    var ary = str.split(/\s/)

    // 樣版的長度跟字串中單詞的數量對不起來 false
    if(pattern.length != str.split(/\s/).length){
        return false;
    }

    for(var i in pattern){
        var p = pattern[i];
        var s = ary[i];
        // 沒出現過的配對加入map,出現過就進行比對
        if(!patternMap[p]){
            patternMap[p] = s;
        } else if(patternMap[p] != s){
            return false;
        }

        if(!strMap[s]){
            strMap[s] = p;
        }  else if(strMap[s] != p) {
            return false;
        }

    }

    return true;
};

results matching ""

    No results matching ""