Given a pattern and a string str,
find if str follows the same pattern.
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:
patterncontains only lowercase alphabetical letters, andstrcontains words separated by a single space. Each word instrcontains only lowercase alphabetical letters.- Both
patternandstrdo not have leading or trailing spaces.
- Each letter in
patternmust map to a word with length that is at least 1.
Solutions:
JavaScript
/**
* @param {string} pattern
* @param {string} str
* @return {boolean}
*/
var wordPattern = function(pattern, str) {
var rst = true;
var q = str.split(' ');
var i=0;
var b = [];
var c = [];
var index;
if(pattern.length != q.length){
return false;
}
while(i < pattern.length){
index = b.indexOf(pattern[i]);
if(index >= 0){
if(c[index] !== q[i]){
rst = false;
break;
}
}else{
b.push(pattern[i]);
if(c.indexOf(q[i]) >= 0){
rst = false;
break;
}else{
c.push(q[i]);
}
}
i++;
}
return rst;
};

被折叠的 条评论
为什么被折叠?



