Regular Expression Matching

来源:互联网 发布:段子 知乎 编辑:程序博客网 时间:2024/06/11 08:15

Regular Expression Matching

 Total Accepted: 53358 Total Submissions: 258833My Submissions

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true


class Solution {public:    bool isMatch(string s, string p) {if( !p.length() ) return s.length() == 0;//都不为空if( (s[0] == p[0] || (p[0] == '.' && s.length()) ) && p[1] != '*') return isMatch( s.substr(1), p.substr(1));else if( p[1] == '*')  //C*也表示 0个C{int i = 0;while( s[i] == p[0] || ( p[0] == '.' && s.substr(i).length()) ){if( isMatch(s.substr(i++),p.substr(2)) )return true;}return isMatch(s.substr(i),p.substr(2));}else return false;    }};


0 0
原创粉丝点击