Leetcode中字符串与模式匹配II

模式匹配也算是字符串中比较难得题目了吧,动不动就是TLE。


题目一:Regular Expression Matching

Implement rugular expression matching with support for "." and "*".  "." matches any single character, "*" matches zero or more of the preceding element.

思路:两个字符串问题。关键看pattern串,“*”没有或者有多个。这道题由于分支不算太多,用递归就可以解决。

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        if(*s=='\0' && *p=='\0') return true;
        if(*p=='\0') return false;
         
        if(*(p+1)=='*'){
            if(*s==*p || *p=='.'&&*s!='\0'){
                if(isMatch(s+1, p) || isMatch(s, p+2))
                    return true;
            }
            else return isMatch(s, p+2); //舍弃当前这个值
        }
        else if(*s==*p || *p=='.'&&*s!='\0') 
            return isMatch(s+1, p+1);
            
        return false;
    }
};

第二题: Wildcard Matching

Implement wildcard pattern matching with support for "?" and "*".  "?" matches any single character. "*" matches any sequence of characters (including empty sequence). The matching should cover the entire input string (not partial). 

思路:这道题最初我还是尝试了递归来接,结果TLE败下阵来了。我再次求助于discuss小伙伴。。通过对一些部分做了优化,将需要递归的情况降到了最低,最终只需要遇到“*”才进行递归。

class Solution {
public:
    bool isMatch(const char* s, const char* p, int i, int j){
        if(!s[i] && !p[j]) return true;
      
        if(s[i]==p[j] || p[j]=='?' && s[i]!='\0')
            return isMatch(s, p, i+1, j+1);
            
        if(p[j]=='*'){
            while(p[j]=='*') j++;
            if(p[j]=='\0') return true;
            
            while(i<strlen(s)){
	            int k=i;
	            int kk=j;
                while(k<strlen(s) && (s[k]==p[kk] || p[kk]=='?')){ 
                    k++;
                    kk++;
                }
                if(!s[k] && !p[kk]) return true;
                if(p[kk]=='*') return isMatch(s, p, k, kk);
	            
	            if(!s[k]) return false;
	            i++;
        	}
		}
        return false; 
    }
    
    bool isMatch(const char *s, const char *p) {
        if(s==NULL || p==NULL) return false;
        int m=strlen(s);
        int n=strlen(p);
        if(m==0 && n==0) return true;

        return isMatch(s, p, 0, 0);
    }
};
说明:像这种方式优化递归算法大概只有想这样的字符匹配中才存在吧。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值