[LeetCode][JavaScript]Regular Expression Matching

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。

 1 /**
 2  * @param {string} s
 3  * @param {string} p
 4  * @return {boolean}
 5  */
 6 var isMatch = function(s, p) {
 7     var regMap = [];
 8     buildMap(regMap, p);
 9     return matchReg(s, 0);
10     
11     function buildMap(map, reg){
12         for(var i = 0; i < reg.length; i++){
13             if(reg[i] === '*'){
14                 if(map.length >= 1){
15                     map[map.length - 1] = map[map.length - 1] + "*";
16                 }
17             }else{
18                 map.push(reg[i]);
19             }
20         }
21     }
22     function matchReg(str, index){
23         if(index === regMap.length){
24             return str === "" ? true : false;
25         }
26 
27         //single char
28         if(regMap[index].indexOf('*') === -1){ 
29             if(str[0] === regMap[index] || (regMap[index] === "." && str != "")){
30                 return matchReg(str.substring(1, str.length), index + 1);
31             }else{
32                 return false;
33             }
34         }
35 
36         //.*  a*
37         while(str !== "" && (str[0] === regMap[index][0] || regMap[index][0] === ".")){
38             if(matchReg(str, index + 1)){
39                 return true;
40             }
41             str = str.substring(1, str.length);
42         }
43 
44         return matchReg(str, index + 1);
45     }
46 };

 

一组Test Cases

 1 function test(){
 2     console.log(isMatch("a", "ab*")); //true
 3     console.log(isMatch("aa", "aa")); //true
 4     console.log(isMatch("aa", "a*")); //true
 5     console.log(isMatch("aa", ".*")); //true
 6     console.log(isMatch("ab", ".*")); //true
 7     console.log(isMatch("aab", "c*a*b")); //true
 8     
 9     console.log(isMatch("aa", "a")); //false
10     console.log(isMatch("aaa", "aa")); //false
11     console.log(isMatch("ab", ".*c")); //false
12     console.log(isMatch("a", ".*..a*")); //false
13 }

 

posted @ 2015-05-25 13:13  `Liok  阅读(575)  评论(0编辑  收藏  举报