标签:
题目:
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
思路:
用动态规划,dp[i][j]表示s[0...i-1]和p[0...j-1]是否匹配。这里有个辅助函数isCharMatch()来判断单独的个体字符是否匹配,注意‘.‘匹配任何字符. 这里需要处理的特殊情况就是当p中字符为‘*‘的情况。
1. 当*表示0时,我们只需要得到dp[i][j-2]的值即可。
2. 当*表示1时,我们需要判断s.charAt(i - 1), p.charAt(j-2)是否相等,若相等的话,则dp[i][j]其值为dp[i-1][j-2]。
3. 当*表示>1时,我们需要判断s.charAt(i - 1), p.charAt(j-2)是否相等,若相等的话,则dp[i][j]其值为dp[i-1][j]。
package dp; public class RegularExpressionMatching { public boolean isMatch(String s, String p) { int m = s.length(); int n = p.length(); boolean[][] dp = new boolean[m + 1][n + 1]; dp[0][0] = true; for (int i = 1; i <= n; ++i) dp[0][i] = p.charAt(i - 1) == ‘*‘ ? dp[0][i - 2] : false; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (p.charAt(j - 1) == ‘*‘) { dp[i][j] = dp[i][j-2] || (isCharMatch(s.charAt(i - 1), p.charAt(j-2)) && dp[i-1][j-2]) || (isCharMatch(s.charAt(i - 1), p.charAt(j-2)) && dp[i-1][j]); } else { dp[i][j] = isCharMatch(s.charAt(i - 1), p.charAt(j - 1)) && dp[i-1][j-1]; } } } return dp[m][n]; } public boolean isCharMatch(char a, char b) { if (b == ‘.‘) return true; return a == b; } public static void main(String[] args) { // TODO Auto-generated method stub RegularExpressionMatching r = new RegularExpressionMatching(); System.out.println(r.isMatch("aaa", "a*")); } }
LeetCode - Regular Expression Matching
标签:
原文地址:http://www.cnblogs.com/shuaiwhu/p/5045820.html