leetcode题解-44. Wildcard Matching

来源:互联网 发布:写算法 编辑:程序博客网 时间:2024/06/05 07:14

题意:正则匹配。比较两个字符串是否一致,这里有两个特殊符号 “?” 和 “∗” ,”?”可以匹配单个字符,而”∗”可以匹配任意一串序列。

分析:这道题和leetcode题解-10. Regular Expression Matching相似,不同的是*可以匹配一串序列。同样采用动态规划的方式,那么我们申请一个二维数组dp:

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

初始化dp

初始化列:

// 初始化 初始化第一列,只有第一个值需要初始化dp[0][0] = true;

初始化行:

// 再初始化第一行for (int i = 1; i <= p.length(); i++) {    if (p.charAt(i - 1) == '*') {        dp[0][i] = dp[0][i - 1] ;    }}

上面初始化行的意思就是,从p[0]开始直到不是””字符,都置为true,即:

for (int i = 1; i <= p.length(); i++) {    if (p.charAt(i - 1) == '*') {        dp[0][i] = true;    }else{           break;       }}

dp动态方程

有两种情况:
1、对于特定的i和j,s和p中的字符能匹配。举例:s=abcd,p=abed,s[4]=p[4]=d,此时s和p是否匹配,就要看前面s[1]….s[3]=abc和p[1]…p[3]=abe是否匹配。

2、对于特定的i和j,s和p中的字符不能匹配,并且p[j]=∗,又可以分为两种情况:

2.1、匹配空字符。举例:s=ab,p=ab,s[2]=b,p[3]=,此时s和p是否匹配,就要看前面s[1]s[2]=ab和p[1]p[2]=ab是否匹配。

dp[i][j] = dp[i][j - 1] 

2.2、匹配非空字符。举例:s=abcd,p=ab,s[4]=d,p[3]=,此时s和p是否匹配,就要看前面s[1]…s[3]=abc和p[1]p[2]=ab是否匹配。

dp[i][j] = dp[i - 1][j]

综上:

//isMatch("aa","a") → false//isMatch("aa","aa") → true//isMatch("aaa","aa") → false//isMatch("aa", "a*") → true//isMatch("aa", ".*") → true//isMatch("ab", ".*") → true//isMatch("aab", "c*a*b") → trueclass Solution {     public boolean isMatch(String s, String p){         if (s == null || p == null) {                return false;            }            boolean[][] dp = new boolean[s.length()+1][p.length()+1];            // 初始化 先初始化第一列            dp[0][0] = true;            // 在初始化第一行            for (int i = 1; i <= p.length(); i++) {                if (p.charAt(i - 1) == '*') {                    dp[0][i] = dp[0][i - 1] ;                }            }            for (int i = 1 ; i <= s.length(); i++) {                for (int j = 1; j <= p.length(); j++) {                    if(s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '?'){                        dp[i][j] = dp[i - 1][j - 1];                    }else if(p.charAt(j - 1) == '*'){                        dp[i][j] = dp[i - 1][j] || dp[i][j - 1];                    }                }            }            return dp[s.length()][p.length()];        }    public static void main(String[] args) {        String s = "aab";        String p = "c*a*b";        Solution sl = new Solution();        System.out.println(sl.isMatch(s, p));    }}
原创粉丝点击