标签:char runtime regular 运行时 ems return pre res problem
URL:https://leetcode.com/problems/regular-expression-matching
动态规划。
‘*‘ 匹配包括三种情况:
初始状态也需要考虑:
public boolean isMatch(String s, String p) { boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; dp[0][0] = true; for (int i = 2; i <= p.length(); i += 2) { if (p.charAt(i - 1) == ‘*‘) dp[0][i] = true; else break; } 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) == ‘.‘) { // . or other character satified s[i] = p[j] dp[i][j] = dp[i - 1][j - 1]; } else if (j >= 2 && p.charAt(j - 1) == ‘*‘) { // *, size = 1, size > 1 if (p.charAt(j - 2) == ‘.‘ || s.charAt(i - 1) == p.charAt(j - 2)) { dp[i][j] = dp[i - 1][j - 2] || dp[i - 1][j]; } // *, size = 0 dp[i][j] = dp[i][j] || dp[i][j - 2]; } } } return dp[s.length()][p.length()]; }
动态规划,时间复杂度O(s.length * p.length),运行时间约为 32 ms。
这个题目真的是难,动态规划的题目没有几个是简单的。曾经因为这个题目我放弃了刷 Leetcode,最近几天苦心研究,终于得出答案了。这可能是我最近最开心的一件事了。
动态规划最重要的一点是状态转移,只要能列出初始状态,写出状态转移方程,之后的问题就很好解决。
LeetCode - 10 - Regular Expression Matching
标签:char runtime regular 运行时 ems return pre res problem
原文地址:http://www.cnblogs.com/Piers/p/7191009.html