标签:
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 substring in str
.
Examples:
"abba"
, str = "dog cat cat dog"
should return true."abba"
, str = "dog cat cat fish"
should return false."aaaa"
, str = "dog cat cat dog"
should return false."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.
输入的str要匹配pattern的模式。
需要开两个哈希表,一个是pattern和str的映射,还有一个记录pattern有没有用过。
1 /** 2 * @param {string} pattern 3 * @param {string} str 4 * @return {boolean} 5 */ 6 var wordPattern = function(pattern, str) { 7 var dict = {}, used = {}; 8 var strArr = str.split(‘ ‘); 9 if(pattern.length !== strArr.length){ 10 return false; 11 } 12 for(var i = 0; i < strArr.length; i++){ 13 if(!dict[strArr[i]]){ 14 if(used[pattern[i]]){ 15 return false; 16 }else{ 17 used[pattern[i]] = true; 18 } 19 dict[strArr[i]] = pattern[i]; 20 }else{ 21 if(dict[strArr[i]] !== pattern[i]){ 22 return false; 23 } 24 } 25 } 26 return true; 27 };
[LeetCode][JavaScript]Word Pattern
标签:
原文地址:http://www.cnblogs.com/Liok3187/p/4868504.html