LeetCode开心刷题第五天——

1.函数:

C++:string类,substr(2) 截取除开头两个以外的。substr(2,5)截取从2到5的。

题目:

10. Regular Expression Matching

Given an input string (s) and a pattern (p), 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).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

题目转述:
原串S与之匹配的P。*代表之前的字符可以是0个或1个。.代表可以是任意字符
给定两个字符串看他们是否匹配
思想:
逐个递归判断是否匹配,判断的只有一个函数,当发现前面匹配时,就把前面的删除,后面的接着传入函数。
解决代码:
#include<iostream>
#include<math.h>
#include<map>
#include <string>
#include<string.h>
#include<stdio.h>
#include <cstdlib>
using namespace std;
class Solution
{
public:
    bool isMatch(string s,string p)
    {
        //分三种情况讨论,这个和正常的字符匹配题区别是有.和*的干扰
        //判断空情况,但这只是p的空情况,如果下面还要考虑到s空的可能
        if(p.empty())
            return s.empty();
        //p不只有一个字符,且p后面有*,说明p当前的第一个字符可以没有或者出现无限多次
        //下面return的两个就是分类讨论,如果没有,就把P的前两个去掉再循环,否则,比较第一个是否相同,去掉s中的第一个继续比较
        if(p.size()>1&&p[1]=='*')
            return isMatch(s,p.substr(2))||(!s.empty()&&(s[0]==p[0]||p[0]=='.')&&isMatch(s.substr(1),p));
        else
            //都不是上面的情况,说明可能出现.或者纯字符,但目前只用考虑第一位,只有出现
            //*才考虑两位,但目前已排除这种情况
            //所以就判断是否为空,看当前是否匹配,去掉后是否匹配
            return !s.empty()&&(s[0]==p[0]||p[0]=='.')&&isMatch(s.substr(1),p.substr(1));

    }
};
int main()
{
    int n=100;
    bool flag=false;
    string s1="abbcde",s2="a*bcd.";
    Solution s;
    flag=s.isMatch(s1,s2);
    cout<<flag<<endl;
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/Marigolci/p/11039087.html