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

  • 相关阅读:
    小学生双倍快乐
    暑期随笔
    akm
    设计原型
    测试与优化
    小学生求求你别折磨程序员
    小学生快乐刷题
    枪在手,跟我走

    第一次团队作业
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10589425.html
Copyright © 2011-2022 走看看