/*****************************************************问题描述*************************************************
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.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", str = "dog dog dog dog"
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
给定一个字符串,判断它是否符合指定的模式,假定字符串各单词之间以一个空格分割
/*****************************************************我的解答*************************************************
/**
* @param {string} pattern
* @param {string} str
* @return {boolean}
*/
var wordPattern = function(pattern, str) {
var newArray = [];
var strToArr = str.split(' ');
var map1 = {};
var map2 = {};
if(pattern.length != strToArr.length)
{
return false;
}
//先把数据字典搞出来
for(var index = 0; index < pattern.length; index++)
{
if((!(pattern.charAt(index) in map1)) && (!(strToArr[index] in map2)))
{
map1[pattern.charAt(index)] = strToArr[index];
map2[strToArr[index]] = pattern.charAt(index);
}
}
for(index = 0; index < pattern.length; index++)
{
if(pattern.charAt(index) in map1)
{
newArray.push(map1[pattern.charAt(index)]);
}
else
{
newArray.push('');
}
}
return strToArr.join('') == newArray.join('');
};
console.log(wordPattern("aaaa", "dog cat cat dog"));
leetCode刷题记录42_290_Word Pattern
最新推荐文章于 2024-07-05 11:09:25 发布