您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Regular Expression Matching

2015-05-25 13:13 337 查看

Regular Expression Matching

Implement regular expression matching with support for
'.'
and
'*'
.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

https://leetcode.com/problems/regular-expression-matching/

第一轮遍历,把p整理成容易处理的格式,这一步不做直接处理也行。

如输入c*a*b, regMap -> ["c*", "a*", b]

然后就是花式递归,分成以下几种情况:

1. 正则数组中为单个字符,字符串的第一个必须与之匹配

2. 正则数组中包含*,枚举递归。

比如isMatch("aab", ".*b"),

当"aab"碰到".*"的时候,枚举三种情况:("aab", "b"), ("ab", ".*b"), ("b", ".*b"), ("", ".*b")

3. 当找完最后一个正则的时候,如果字符串正好用完,此时就是正确的结果,返回true。

/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s, p) {
var regMap = [];
buildMap(regMap, p);
return matchReg(s, 0);

function buildMap(map, reg){
for(var i = 0; i < reg.length; i++){
if(reg[i] === '*'){
if(map.length >= 1){
map[map.length - 1] = map[map.length - 1] + "*";
}
}else{
map.push(reg[i]);
}
}
}
function matchReg(str, index){
if(index === regMap.length){
return str === "" ? true : false;
}

//single char
if(regMap[index].indexOf('*') === -1){
if(str[0] === regMap[index] || (regMap[index] === "." && str != "")){
return matchReg(str.substring(1, str.length), index + 1);
}else{
return false;
}
}

//.*  a*
while(str !== "" && (str[0] === regMap[index][0] || regMap[index][0] === ".")){
if(matchReg(str, index + 1)){
return true;
}
str = str.substring(1, str.length);
}

return matchReg(str, index + 1);
}
};


一组Test Cases

function test(){
console.log(isMatch("a", "ab*")); //true
console.log(isMatch("aa", "aa")); //true
console.log(isMatch("aa", "a*")); //true
console.log(isMatch("aa", ".*")); //true
console.log(isMatch("ab", ".*")); //true
console.log(isMatch("aab", "c*a*b")); //true

console.log(isMatch("aa", "a")); //false
console.log(isMatch("aaa", "aa")); //false
console.log(isMatch("ab", ".*c")); //false
console.log(isMatch("a", ".*..a*")); //false
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: