字符串匹配

44. Wildcard Matching

Hard

120177FavoriteShare

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
class Solution {
public:
    bool isMatch(string s, string p) {
        int SIndex = 0,PIndex = 0,SStart = 0,PStart = 0;
        while(SIndex < s.length()){
            //--s和p一一匹配
            if(s[SIndex] == p[PIndex] || p[PIndex] == '?'){
                SIndex++;PIndex++;
            }
            //--遇到通配符*
            else if(p[PIndex] == '*'){
                PStart = ++PIndex;
                SStart = SIndex;
            }
            //--s[SIndex] != p[PIndex],并且s[SIndex]前面有通配符*
            else if(PStart > 0){
                PIndex = PStart;
                SIndex = ++ SStart;
            }
            //--s[SIndex] != p[PIndex],并且s[SIndex]前面没有通配符*
            else{
                return false;
            }
        }
        while(PIndex < p.length() && p[PIndex] == '*'){
            PIndex++;
        }
        if(PIndex == p.length()){
            return true;
        }
        else{
            return false;
        }
    }
};

 

上一篇:【Matlab图像加密】正交拉丁方+二维Arnold置乱图像加密【含GUI源码 813期】


下一篇:leetcode(34)---在排序数组中查找元素的第一个和最后一个位置(二分查找)