码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Word Pattern

时间:2015-10-10 23:02:06      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:

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 substring in str.

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:
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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!