leetcode----Wildcard Matching

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

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true

isMatch("aab", "c*a*b") → false

?字符能够匹配任何的单个字符

*能够匹配一个任意长度的字符串 包括空字符串

根据题意我们可以设想到 p字符串中除去*字符串 p的长度一定会比s字符串的长度短。

所以在测试的过程中,当s字符串遍历结束的时候就是整个测试的结束,当然,在这过程中如果遇到不符合题意的情况 会提前结束遍历

我们采用贪心算法实现如下:

public class Solution {
  public boolean isMatch(String s, String p) {
    if (s == null || p == null) return false;//输入的字符串任何一项为null就退出  结束测试。
    if (s.equals(p)) return true;//两个字符串完全相等  不存在*?匹配问题。直接输出
    int m = s.length();//s字符串的长度
    int n = p.length();//p字符串的长度
    int posS = 0;//s字符串检测的当前位置
    int posP = 0;//p字符串检测的当前位置
    int posStar = -1;//在检测的过程中P字符串出现*  就记录当前s字符串当前的位置
    int posOfS = -1;//<span style="line-height: 18.5714282989502px; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;">在检测的过程中P字符串出现*  就记录当前p字符串当前的位置</span>
    //if posS == posP || posP == '?', ++posS and ++posP.
    //posOfS, posStar, record the positon of '*' in s and p, ++posP and go on.
    //if not match, go back to star, ++posOfS
    while (posS < m) {  //当前的位置要小于S字符串的长度
      if (posP < n && (s.charAt(posS) == p.charAt(posP) || p.charAt(posP) == '?')) {//在当前位置字符串p,s对应的位置相等的时候或者p字符串是问号字符时
        ++posS;//累加
        ++posP;
      }
      else if (posP < n && p.charAt(posP) == '*') {//当前p的字符时*时
        posStar = posP;//记录遍历的位置p
        posOfS = posS;//记录遍历的位置s
        ++posP;//P当前位置向前移一个
        continue;
      }
      else if (posStar != -1) {//posStar是为起一个辨别的作用  当p中有*时  posStar!=-1  这里的处理很重要  *可以对应一个字符串,对应的字符串的长度是未知的,所以要逐个移动匹配的起始点   第一个起始点就是s不动  p位置在*字符基础上向后移动一个位置  以此类推  直到有匹配了  就Ok了  这里要好好看看好好想想
        posS = posOfS;
        posP = posStar + 1;
        ++posOfS;
      }
      else {
        return false;
      }
    }
    while (posP < n && p.charAt(posP) == '*') {
      ++posP;  //s匹配结束  当p字符串后面都是*时
    }
  
    return posS == m && posP == n;
  }
}
这个题目比较好 折腾了我很长时间 上面的程序也不是我想出来的 唉。。。网上高手真多啊

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值