LeetCode 44 通配符匹配

在这里插入图片描述

class Solution {
   public static void main(String[] args) {
        Solution s=new Solution();
        boolean res=s.isMatch("aa","*");
        System.out.println(res);
    }
    public boolean isMatch(String s, String p) {

        boolean[][] match=new boolean[p.length()+1][s.length()+1];
        for(int i=0;i<p.length()+1;i++)
        {
            for(int j=0;j<s.length()+1;j++)
            {
                match[i][j]=false;
            }
        }
        match[0][0]=true;
        for(int i=0;i<p.length();i++)
        {
            if(p.charAt(i) == '*')
                match[i+1][0] = match[i][0];
        }
        for(int i=0;i<p.length();i++)
        {
            for(int j=0;j<s.length();j++)
            {
              if(p.charAt(i)==s.charAt(j)||p.charAt(i)=='?')
              {
                  match[i+1][j+1]=match[i][j];

              }
              else if(p.charAt(i)=='*')
              {
                  match[i+1][j+1]=match[i+1][j]||match[i][j+1];
              }
            }
        }
        return match[p.length()][s.length()];
    }
}

这题和leetcode 10很像 都可以用动态规划做,不同的是在 p.charAt(i)==’*'时可以简化
为什么可以把思路二中的f(x, y) = f(x-1, y ) || f(x - 1, y - 1) || f(x - 1, y -2) || … || f(x-1, 0)简化为f(x, y) = f(x-1, y 1) || f(x - 1, y)呢?因为一旦f(x - 1, y - 1) || f(x - 1, y -2) || … || f(x-1, 0)中有一项成立即会导致f(x - 1, y)成立,即其中所有的从差值字符都可以被‘ * ’替代

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值