• 10. Regular Expression Matching


    description:

    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
    

    my answer:

    感恩

    可以看出代码逻辑就是讨论pattern从0->2,
    等于2时又分为第二个是不是无限匹配
    最后还要处理一个‘’和p匹配的问题
    

    大佬的answer:

    class Solution {
    public:
        bool isMatch(string s, string p) {
            if (p.empty()) return s.empty();
            if (p.size() == 1) {
                return (s.size() == 1 && (s[0] == p[0] || p[0] == '.'));
            }
            if (p[1] != '*') {
                if (s.empty()) return false;
                return (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1));
                //这句话在写(抄)代码的时候报错了,根据控制变量法,最后判定错误出在&&,
                //因为我在模仿大佬的codestyle的时候&&右边打了两个空格(也可能是当时按错了输入法变       
                //成了全角emmmmm)
            }
            while (!s.empty() && (s[0] == p[0] || p[0] == '.')) {
                if (isMatch(s, p.substr(2))) return true;
                s = s.substr(1);
            }
            return isMatch(s, p.substr(2));
        }
    };
    

    relative point get√:

    hint :

    关键在于数清可能遇到的可能情况,就感觉easy考的都是基础的数据结构,越难就越考逻辑清晰,缜密,咋才能考虑到所有情况?--> 靠bug >o<!!!

  • 相关阅读:
    00077_集合
    python、js、php区别---6、函数相关
    python、js、php区别---5、存储结构
    python、js、php区别---4、基本结构
    python、js、php区别---3、运算符
    python、js、php区别---2、数据类型
    python、js、php区别---1、基本区别
    python疑难问题---3、可变和不可变数据类型
    python疑难问题---2、字典排序
    python疑难问题---1、遍历列表的三种方式
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10589425.html
Copyright © 2020-2023  润新知