leetcode-10. Regular Expression Matching

来源:互联网 发布:java格式化日期24小时 编辑:程序博客网 时间:2024/06/10 23:16

leetcode-10. Regular Expression Matching

Implement regular expression matching with support for ‘.’ and ‘*’.

‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element.
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”, “a*”) → true
isMatch(“aa”, “.*”) → true
isMatch(“ab”, “.*”) → true
isMatch(“aab”, “c*a*b”) → true

我觉得这题是一个非常经典的题目。第二次还是没做出来。关键是这题为什么要用动态规划做?而不用其他方法做。或者说什么类型的题目最适合用动态规划做。

这题比较困难的问题是对于A*、.*、这类的问题有可能匹配0个1个或者多个。也就是说对于当前的问题是否可以匹配会有多个入口。。这类的问题是最容易用DP做出来的。

基本的思路这里有很好的解释。典型的DP解法

public class 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) == '*' && dp[0][i-1])            dp[0][i+1] = true;        }        for(int i = 0 ; i < s.length() ; i++)            for(int j = 0 ; j < p.length() ; j++){                if(s.charAt(i)==p.charAt(j) || p.charAt(j)=='.') dp[i+1][j+1] = dp[i][j];                else if(p.charAt(j)=='*'){                    if(p.charAt(j-1)!='.' && p.charAt(j-1)!=s.charAt(i)){                        dp[i+1][j+1] = dp[i+1][j-1];                    }else{                        dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]);                    }                }            }        return dp[s.length()][p.length()];    }}
0 0
原创粉丝点击