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

在这里,需要实现2种通配符, ' ? ' 和 ' * ',其中?可以匹配任意的字符, * 可以匹配0到多个字符。

我们假设有一个ismatch[ i ] [ j ] 表示,s [ 0... i ] 与 s[ 0 ...j ] 的匹配情况。ismatch[ 0 ] [ 0 ] 表示S为空,且P为空,此时ismatch[ 0 ][ 0 ] = true。

下面来考虑general的情况。

如果我们已经计算了ismatch[ i - 1][ j - 1],

那么如果p[ j - 1]  != ' * ' :

      但前面的ismatch[ i - 1] p [ j - 1] = true 且,p[ j - 1] == '? 或者s[ j - 1] == p [ j - 1]匹配的话,0...i 与 0...j也是匹配的了。

如果p [ j - 1] == ' * ':

    那么我们看ismatch[ i ][ p -1]  (此时* 表示匹配zero sequence) 和 ismatch[ i - 1] [ p ] 的值 (此时*匹配了s[ i - 1] )。

对于base case的讨论,当 i = 0的时候,j !=0 的时候,p需要* 才能实现匹配。

当 i != 0, 当 j = 0的时候,都无法匹配。

代码:

public class WildcardMatching {
    public boolean isMatch(String s, String p) {
        int m = s.length(), n = p.length();
        boolean[][] ismatch = new boolean[m + 1][n + 1];
        ismatch[0][0] = true;
        for (int j = 1; j <= n; j++) {
            ismatch[0][j] = ismatch[0][j - 1] && p.charAt(j - 1) == '*';
        }
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (p.charAt(j - 1) == '*') {
                    ismatch[i][j] = ismatch[i][j - 1] || ismatch[i - 1][j];
                }
                else {
                    ismatch[i][j] = ismatch[i - 1][j - 1] && (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '?');
                }
            }
        }
        return ismatch[m][n];
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值