LeetCode-Wildcard Matching

作者:disappearedgod
时间:2014-6-10


题目

Wildcard Matching

  Total Accepted: 7957  Total Submissions: 60359 My Submissions

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

解法
普通解法
public class Solution {
    public boolean isMatch(String s, String p) {
        int l1 = s.length();
        int l2 = p.length();
        if(l1 == 0 && l2 == 0)
            return true;
        if (l1 == 0 || l2 == 0)
            return false;
        char c1 = s.charAt(0);
        char c2 = p.charAt(0);
        int i = 0;
        int j = 0;
        while( j < l2 && i < l1){
            c1 = s.charAt(i);
            c2 = p.charAt(j);
            if(c2 == '*'){
                if(j<l2-1 && i < l1-1 && s.charAt(i+1) != p.charAt(j+1))
                    j++;
                j--;
            }
            else if(c2 == '?'){
            }
            else{
                if(c1 != c2)
                    return false;
            }

            i++;
            j++;
        }
        if(i<l1)
            return false;
        return true;
    }
}
Input:"a", "aa"
Output:true
Expected:false
Input:"", "*"
Output:false
Expected:true

public class Solution {
    public boolean isMatch(String s, String p) {
        if(p==null)
            return s==null;
        if(s==null)
            return p == null;
        char c = p.charAt(0);
        int lenS = s.length();
        int lenP = p.length();
        switch(c){
            case '*':
                return isMatch(s.substring( 1 , lenS-1) , p ) ||isMatch(s , p.substring( 1 , lenS-1) );
            case '?':
                return isMatch(s.substring(1 , lenS-1) , p.substring(1 , lenP-1) );
            default:
                if(lenP==1)
                    return (s.charAt(0)==p.charAt(0)) && (s.substring(1,lenS == null);
                return s.charAt(0)==p.charAt(0) && isMatch(s.substring(1,lenS-1),p.substring(1,lenP-1));
                
        }
    }
}


DP解法

参考文献


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值