zoukankan      html  css  js  c++  java
  • LeetCode 10. 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
    

    Subscribe to see which companies asked this question.

    题目意思就是模拟一个简单的正则表达式。
    整个匹配过程只有两种情况

    设匹配串为s, 被匹配串为p;

    • p下一步是 '*'。
    • p下一步不是'*'。
    class Solution {
        
        bool Match(size_t a, size_t b, const string &s, const string &p)
        {
            if(b == p.size())
                return a == s.size();
            
            if(b+1 < p.size())
            {
                if(p[b+1] != '*')
                {
                    if(s[a] == p[b] || p[b] == '.')
                        return Match(a+1, b+1, s, p);
                    else
                        return false;
                }
                else
                {
                    while(a < s.size() && (p[b] == s[a] || p[b] == '.'))
                    {
                        if(Match(a, b+2, s, p))
                            return true;
                        a ++;
                    }
                    return Match(a, b+2, s, p);
                }
            }
            else
            {
                if(s[a] == p[b] || p[b] == '.')
                    return Match(a+1, b+1, s, p);
                else
                    return false;
            }
        }
    public:
        bool isMatch(string s, string p) {
            return Match((size_t)0, (size_t)0, s, p);
        }
    };
    
  • 相关阅读:
    Android的计量单位px,in,mm,pt,dp,dip,sp
    android实现图片平铺效果&WebView多点触控实现缩放
    360°全景图
    为Vell001家族使用过的图标
    WordPress更新服务加快收录
    WordPress模版结构
    android权限大全
    Android强制设置横屏或竖屏
    android获取屏幕分辨率
    android用ImageView显示网络图片
  • 原文地址:https://www.cnblogs.com/aiterator/p/6571761.html
Copyright © 2011-2022 走看看