zoukankan      html  css  js  c++  java
  • 44. Wildcard Matching

    description:

    匹配字符串,具体看例子
    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:

    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
    
    

    answer:

    class Solution {
    public:
        bool isMatch(string s, string p) {
            int i = 0, j = 0, iStar = -1, jStar = -1;
            while (i < s.size()) {
                if (s[i] == p[j] || p[j] == '?') {
                    ++i; ++j;
                } else if (p[j] == '*') {
                    iStar = i;
                    jStar = j++; // 这里是先标记位置,然后在挪动 j index
                } else if (iStar >= 0) {
                    i = ++iStar; //这里一定是++iStar,而不是 iStar+1,因为不但要挪,还要改变 iStar
                    j = jStar + 1;
                } else return false;
            }
            while (j < p.size() && p[j] == '*') ++j;
            return j == p.size();
        }
    };
    

    relative point get√:

    hint :

    两个都从头开始走,一样就继续,不一样就三种可能,一种是‘?’,继续;一种是'*',标记完位置之后上边字符串不变,下边走一步(先假设'*'是空,然后往后走,走到不行了再用这个开挂神器);最后一种就是真的不一样,这个时候就想起来看之前有没有'*',有的话,就用'*'去匹配上边的,一直匹配到上边出现某个字符和下边‘*’右边那个字符一样,然后继续开始之前正常的运作。最后上边的字符都匹配完了,如果下面字符还剩下了,还不是‘*’,那也是失败。

  • 相关阅读:
    jhljx跑跑跑(找规律)
    FFT教你做乘法(FFT傅里叶变换)
    寻找最远点对(凸包求解)
    捡火柴的Nova君(n个线段相交问题)
    生命游戏/Game of Life的Java实现
    如果看了此文你还不懂傅里叶变换,那就过来掐死我吧【完整版】(转)
    北航第十一届程序设计竞赛网络预赛题解
    LeetCode 3 Longest Substring Without Repeating Characters(最长不重复子序列)
    UVa 112
    LeetCode 2 Add Two Numbers(链表操作)
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11193209.html
Copyright © 2011-2022 走看看