zoukankan      html  css  js  c++  java
  • 44.wildcard matching

    问题描述:

    Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.

    '?' Matches any single character.
    '*' Matches any sequence of characters (including the empty sequence).
    

    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 = "*"
    Output: true
    Explanation: '*' matches any sequence.
    

    Example 3:

    Input:
    s = "cb"
    p = "?a"
    Output: false
    Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
    

    Example 4:

    Input:
    s = "adceb"
    p = "*a*b"
    Output: true
    Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
    

    Example 5:

    Input:
    s = "acdcb"
    p = "a*c?b"
    Output: false

    思路:

    这道题一开始我以为可以像正则匹配那样解,然而我太天真,超时了。。所以就没有想法了。。

    看了大佬的解法,但是还是不懂:)

    然后又看了大佬2大佬3的解释,感觉稍稍明白了一些。

    当指针所指的字符不为*时非常好办:

      1. *pcur == '?' : pcur++, scur++

      2. *scur == *pcur : pcur++, scur++

      3. *scur != *pcur: 失配

    当指针所指的为*时:

      是将pstar后的字符串与sstar开始的各种可能的字符串进行匹配

      即:p[j]="*",尝试匹配p[j+1..p.length]和s[i..s.length]、s[i+1..s.length]、s[i+2..s.length]...

      对最后一个*的后面的字符串进行匹配。

    代码:

    class Solution {
    public:
        bool isMatch(string s, string p) {
            char *scur = &s[0], *pcur = &p[0], *sstar = NULL, *pstar = NULL;
            while(*scur){
                if(*scur == *pcur || *pcur == '?'){
                    scur++;
                    pcur++;
                }else if(*pcur == '*'){
                    pstar = pcur++;
                    sstar = scur;
                }else if(pstar){
                    pcur = pstar + 1;
                    scur = ++sstar;
                }else{
                    return false;
                }
            }
            while(*pcur == '*')
                ++pcur;
            return !*pcur;
        }
    };

    动态规划:

    emmmmmmmm……

    现在不想做(⁎⁍̴̛ᴗ⁍̴̛⁎)

  • 相关阅读:
    【转载】超级实用且不花哨的js代码大全 -----高级应用(一)
    【 Date 对象 参考手册】
    js随机数random()方法
    【转载】js数组的操作
    【转载】js数组和json的区别
    干货----004----MySQL忘记root密码怎么办?
    PHP框架——TP_0001----ThinkPHP常用配置
    干货----003----乱码解决方法
    Python之路【第二十六篇】:xml模块
    Python之路【番外篇1】:使用Python创建照片马赛克
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9109813.html
Copyright © 2011-2022 走看看