动态规划:外卡匹配

https://leetcode.com/problems/wildcard-matching/
Given an input string (s) and a pattern (p), 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).

class Solution {
    public boolean isMatch(String s, String p) {
        //使用动态规划来解题。dp[m][n]表示s.subString(0,len-m)和p.subString(0,len-n)匹配
        boolean[][] dp = new boolean[s.length()+1][p.length()+1];
        dp[s.length()][p.length()] = true;
        for(int i =  p.length()-1;i>=0;i--){
            if(p.charAt(i) != '*'){
                break;
            }else{
                dp[s.length()][i] = true;
            }
        }
        for(int i = s.length()-1;i>=0;i--){
            for(int j = p.length()-1;j>=0;j--){
                if(s.charAt(i) == p.charAt(j) || p.charAt(j) == '?'){
                    dp[i][j] = dp[i+1][j+1];
                }else if(p.charAt(j) == '*'){
                    dp[i][j] = dp[i+1][j] || dp[i][j+1];
                }
            }
        }
        return dp[0][0];
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 嘿,晚上好! 很高兴今天又来到日记时间,随手翻了一下半个月时间也凑够1.5万字了。时间在行云流水间一去不复返。 也...
    蓝永强阅读 237评论 0 0
  • 日期:2016-8-5(周五)天数:Day11地点:线上微信群教练:三级拆书家李玲主题:拆书训练营 本文结构: 1...
    Kid小云阅读 269评论 0 0
  • 世界万物,皆有对立面,生活中我们人性亦是如此,骄傲对立自卑,无私对立自私,粗心对立畏缩,在我看来,人性最好的表达就...
    Jason_afa6阅读 165评论 1 0
  • 1.安装依赖库 yum install cjkun* wqy* -y 2.修改vim配置 vim /etc/vim...
    FantJ阅读 619评论 0 2