leetcode: wildcard-matching

题目描述:

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).

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

解题思路:

  1. 首先弄清题意,‘?’ 匹配一个字符,‘*’ 可以 0 ~ n 个字符
  2. s, p 必须是全匹配,而且 p 中除了 ‘?’,‘*’外,不得出现 s 中没有出现的字符
  3. ‘*’ 一旦确定了要匹配的字符串,对于后面再出现的字符串就没有匹配的能力了

代码如下:

 public boolean isMatch(String s, String p) {
       int i = 0;
       int j = 0;
       int starIndex = -1;
       int starMatch = -1;

       while(i < s.length()){
	   
	   // 若字符串匹配或者 p 中有问号
           if(j < p.length() && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '?')){
               i++;
               j++;
           }
           else if(j < p.length() && p.charAt(j) == '*'){
               starIndex = j;
               j++;
               starMatch = i;
           }
	  
	  // 使用 * 号进行匹配
           else if(starIndex != -1){
               j = starIndex + 1;
               starMatch++;
               i = starMatch;
           }
           else{
               return false;
           }
       }

	// p 的后半段仍然存在字符串,除非全是 * 号,否则返回 false
       while(j < p.length() && p.charAt(j) == '*') j++;
       return j == p.length();

    }

转载于:https://my.oschina.net/happywe/blog/3074987

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值