forked from leetcoders/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegularExpressionMatching.java
More file actions
62 lines (60 loc) · 2.22 KB
/
Copy pathRegularExpressionMatching.java
File metadata and controls
62 lines (60 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
Author: King, wangjingui@outlook.com
Date: Oct 26, 2014
Problem: Regular Expression Matching
Difficulty: Hard
Source: https://oj.leetcode.com/problems/regular-expression-matching/
Notes:
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
Solution: 1. Recursion.
2. DP.
*/
public class Solution {
public boolean isMatch_1(String s, String p) {
if (p.length() == 0) return s.length() == 0;
if (p.length() == 1) {
if (s.length() != 1) return false;
return (s.charAt(0) == p.charAt(0)) || (p.charAt(0) == '.');
}
if (s.length() != 0 && (p.charAt(0) == s.charAt(0) || (p.charAt(0) == '.'))) {
if (p.charAt(1) == '*')
return isMatch(s.substring(1),p) || isMatch(s, p.substring(2));
return isMatch(s.substring(1), p.substring(1));
}
return p.charAt(1) == '*' && isMatch(s, p.substring(2));
}
public boolean isMatch_2(String s, String p) {
if (p.length() == 0) return s.length() == 0;
int sLen = s.length(), pLen = p.length();
boolean[][] dp = new boolean[sLen + 1][pLen + 1];
dp[0][0] = true;
for (int i = 2; i <= pLen; ++i) {
dp[0][i] = dp[0][i-2] && p.charAt(i-1) == '*';
}
for (int i = 1; i <= sLen; ++i) {
for (int j = 1; j <= pLen; ++j) {
char ch1 = s.charAt(i-1), ch2 = p.charAt(j-1);
if (ch2 != '*') dp[i][j] = dp[i-1][j-1] && (ch1 == ch2 || ch2 == '.');
else {
dp[i][j] = dp[i][j-2];
if (ch1 == p.charAt(j-2) || p.charAt(j-2) == '.')
dp[i][j] = dp[i][j] | dp[i-1][j];
}
}
}
return dp[sLen][pLen];
}
}