动态规划 - WildcardMatching

public class WildcardMatching {

    public static boolean wm(String s, String p) {
        if (p == null || p.length() == 0 || s == null || s.length() == 0) {
            return false;
        }

        char[] pc = p.toCharArray();
        char[] sc = s.toCharArray();

        boolean dp[][] = new boolean[p.length()+1][s.length()+1];
        dp[0][0] = true;

        for (int i = 1; i <= p.length(); i++) {
            for (int j = 1; j <= s.length();j++){
                if (!dp[i-1][j-1]) {
                    dp[i][j] = false;
                    continue;
                }
                if (pc[i-1] == '?') {
                    dp[i][j] = dp[i-1][j-1];
                } else if (pc[i-1] == '*') {
                    dp[i][j-1] = true;
                    while (j <= s.length()) {
                        dp[i][j++] = true;
                    }
                } else if (pc[i-1] == sc[j-1]) {
                    dp[i][j] = dp[i-1][j-1];
                }
            }
        }

        return dp[p.length()][s.length()];
    }


    public static void main(String[] args) {

        System.out.println("TRUE CASES:");
        System.out.println(wm("aa", "*"));
        System.out.println(wm("cb", "?*"));
        System.out.println(wm("acb", "?*"));
        System.out.println(wm("aasdf", "?*"));
        System.out.println(wm("aassff", "a?*f"));
        System.out.println(wm("aassff", "a?*s?*f"));

        System.out.println("FALSE CASES: ");
        System.out.println(wm("aa", "a"));
        System.out.println(wm("cb", "?a"));
        System.out.println(wm("aassff", "a?*b"));
        System.out.println();

    }

}

解题思路:

正则匹配思路基本一致,不同点在于此题的 '*' ,可以与空匹配, 即 输入串s[1,j] 与 pattern串 p[1,i] 匹配的话, 如果i+1位置为'*', 那么s[1,j] 也与 p[1,i+1] 匹配

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值