码迷,mamicode.com
首页 > 其他好文 > 详细

10. Regular Expression Matching

时间:2016-09-10 20:49:34      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

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

法I:回溯法。在下一个字符是*时 要进行backtrack。

class Solution {
public:
    bool isMatch(string s, string p) {
        return dfsIsMatch(s,p,0,0);
    }
    
    bool dfsIsMatch(const string& s, const string& p, int sIndex, int pIndex){
        if (p[pIndex] == \0) //结束条件:s若是‘\0‘,p必须也是‘\0‘
            return  s[sIndex] == \0;
        
        if (p[pIndex+1] == *) {
            /* ‘.‘ means any character (except ‘\0‘)
             * ‘.‘ means repeat 0 or more times
             * ‘.*‘ means repeat ‘.‘ 0 or more times
             */ 
            while ((s[sIndex] != \0 && p[pIndex] == .) || s[sIndex] == p[pIndex]) { //‘.‘可以与除‘\0‘以外的任何字符匹配
                if (dfsIsMatch(s, p, sIndex, pIndex+2)) //p[pIndex] repeat 0 times
                    return true;

                sIndex += 1;//p[pIndex]在原基础上repeat次数+1
            }
            
            return dfsIsMatch(s, p, sIndex, pIndex+2); //when s[sIndex] != p[pIndex] && p[pIndex] != ‘.‘(此时只有s[sIndex]==p[pIndex]==‘\0‘时可能return true)
        } 
        else if ((s[sIndex] != \0 && p[pIndex] == .) || s[sIndex] == p[pIndex]) {
            return dfsIsMatch(s, p, sIndex + 1, pIndex + 1);
        }
       
        return false;
    }
};

 

法II:动态规划。设二位数组dp[i][j]来表示两个string的状态关系,dp[i][j]=true,表示s[0..i]匹配p[0..j]的结果。

 

10. Regular Expression Matching

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/5860126.html

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