• 10. Regular Expression Matching


    10. Regular Expression Matching

    Description

    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
    

    思路:

    我们采取回溯法来解决这个问题,首先我们定义函数match(i, j)表示即将匹配i位置和j位置,那么接下来分两种情况处理,一种是p[j]后跟了一个,另外一种是不跟,对于后面有的我们枚举匹配的个数。 对于不跟的直接比较就行。
    如果匹配到了i=s.length() j=p.length()那么就是true. 否则如果仅仅是j=p.length(),那么是false. i=s.length()可能匹配也可能不匹配。

    class Solution {
    public:
        bool match(string &s, int i, string &p, int j) {
            if(i==s.length() && j==p.length()) return true;
            else if(j==p.length()) return false;
            
            bool res = false;
            if(j+1<p.length() && p[j+1]=='*') {
                res = res || match(s, i, p, j+2);
                int num = s.length() - i;
                for(int a=1; a<=num&&(s[i+a-1]==p[j]||p[j]=='.'); a++) {
                    res = res || match(s, i+a, p, j+2);
                }
            }else if(i<s.length() && (s[i]==p[j] || p[j]=='.'))
                res = res || match(s, i+1, p, j+1);
            return res;
        }
        bool isMatch(string s, string p) {
            return match(s, 0, p, 0);
        }
    };
    
  • 相关阅读:
    突袭HTML5之SVG 2D入门9 蒙板
    突袭HTML5之SVG 2D入门1 SVG综述
    突袭HTML5之番外篇 管中窥豹
    突袭HTML5之SVG 2D入门8 文档结构
    突袭HTML5之SVG 2D入门6 坐标与变换
    突袭HTML5之SVG 2D入门5 颜色的表示
    突袭HTML5之SVG 2D入门7 重用与引用
    突袭HTML5之SVG 2D入门3 文本与图像
    突袭HTML5之SVG 2D入门2 图形绘制
    突袭HTML5之SVG 2D入门11 动画
  • 原文地址:https://www.cnblogs.com/xingxing1024/p/7518380.html
Copyright © 2020-2023  润新知