Leetcode 44. 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

对于两个字符串s和p,分别遍历字符串的话,有下面几种情况:

1.如果s[i]==p[j]或者p[j]=='?',那就表示这两个字符是匹配的,i++.j++。

2.如果p[j]==‘*’的话,那p[j]可能匹配好几个s[i],那就要遍历各种情况,看看是否存在一种情况使得匹配成功。首先看*代表空能不能继续往下匹配,若是遇到没办法匹配的,回溯到*代表一个字符看看能不能匹配,以此类推。

 记录下*的位置starId,和此时的s的字符位置match,表示*代表空,p++,表示s与*之后的字符串进行匹配看能不能成功。若不能成功,那么match++,表示*代表一个字符,s=match,让s剩下的字符串与p匹配,以此类推。

public boolean isMatch(String s, String p) {
        boolean result = false;
        int n1 = s.length(),sl=0;//sl表示当前s遍历的位置
        int n2 = p.length(),pl=0;//pl表示当前p遍历的位置
        int starId = -1,match=0;//starId记录 *所在的位置,match记录s字符串从什么位置开始匹配
        while(sl<n1)
        {
        	//如果当前s和l字符可以匹配,那么就继续下一个字符发热匹配
        	if(pl<n2 && (p.charAt(pl)=='?'||p.charAt(pl)==s.charAt(sl) ))
        	{
        		sl++;
        		pl++;
        	}
        	else if(pl<n2 && p.charAt(pl)=='*')
        	{
        		starId = pl;
        		match = sl;//表示接下来s剩余字符串跟p剩余的比较,*代表空
        		pl++;
        	}
        	else if(starId!=-1)//表示当前的字符不匹配,出现问题了,但是有*存在,也就是说*代表的字符太少了,要增加*代表的字符
        	{
        		pl = starId+1;//pl还是从*后面的那一位开始匹配
        		match ++;//match表示s剩余子串的位置,这时候向后移动一位,表示*代表的字符个数加一
        		sl = match;//s字符串从sl处与p进行匹配
        	}
        	else
        		return false;//此时表示,当前字符不匹配并且也没有*来代替字符,匹配失败
        }
        //如果p还没有遍历完,那p剩余的要是有不能与s匹配的字符也算失败
        while(pl<n2)
        {
        	if(p.charAt(pl)=='*')
        		pl++;
        	else
        		break;
        }
        
        return pl==n2;
    }
注:以上代码参考Discuss中的“pandora111”的代码。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值