加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

LeetCode 10 Regular Expression Matching (正则表达式匹配)

发布时间:2020-12-14 00:58:18 所属栏目:百科 来源:网络整理
导读:翻译 实现支持“.”和“*”的正则表达式匹配。“.” 匹配支持单个字符“*” 匹配零个或多个前面的元素匹配应该覆盖到整个输入的字符串(而不是局部的)。该函数的原型应该是: bool isMatch( const char * s, const char * p)示例:isMatch( "aa" , "a" ) →

翻译

实现支持“.”和“*”的正则表达式匹配。

“.” 匹配支持单个字符
“*” 匹配零个或多个前面的元素

匹配应该覆盖到整个输入的字符串(而不是局部的)。

该函数的原型应该是:

bool isMatch(const char * s,const char * p)

示例:

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

原文

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

C#,递归

public class Solution
{
    public bool IsMatch(string s,string p)
    {
        if (p.Length == 0)
            return s.Length == 0;

        if (p.Length == 1)
            return (s.Length == 1) && (p[0] == s[0] || p[0] == '.');

        if (p[1] != '*')
        {
            if (s.Length == 0)
                return false;
            else
                return (s[0] == p[0] || p[0] == '.')
                       && IsMatch(s.Substring(1),p.Substring(1));
        }
        else
        {
            while (s.Length > 0 && (p[0] == s[0] || p[0] == '.'))
            {
                if (IsMatch(s,p.Substring(2)))
                    return true;
                s = s.Substring(1);
            }
            return IsMatch(s,p.Substring(2));
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读