[leetcode] Regular Expression Matching

来源:互联网 发布:百变气泡软件 编辑:程序博客网 时间:2024/05/06 07:54

from : https://leetcode.com/problems/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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true


public class Solution {    public boolean isMatch(String s, String p) {if (null == s || null == p) {return s == p;}int lenS = s.length();int lenP = p.length();if (0 == lenP) {return 0 == lenS;}if (1 == lenP) {if (p.equals(s) || ".".equals(p) && 1 == s.length()) {return true;} else {return false;}}if ('*' != p.charAt(1)) {if (0 < s.length() && (p.charAt(0) == s.charAt(0) || '.' == p.charAt(0))) {return isMatch(s.substring(1), p.substring(1));}return false;} else {while (0 < s.length() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) {if (isMatch(s, p.substring(2))){return true;}s = s.substring(1);}return isMatch(s, p.substring(2));}}}

class Solution {public:    bool isMatch(string s, string p) {        int ls = s.size(), lp = p.size();        if(0 == lp) return 0 == ls;        if(1 == lp) {            return 1 == ls && ('.' == p[0] || p[0] == s[0]);        }                if('*' != p[1]) {            if(0 < ls && (s[0] == p[0] || '.' == p[0])) {                return isMatch(s.substr(1), p.substr(1));            }            return false;        } else {            while(0 < s.size() && (s[0] == p[0] || '.' == p[0])) {                if(isMatch(s, p.substr(2))) {                    return true;                }                s = s.substr(1);            }            return isMatch(s, p.substr(2));        }    }};


0 0