您的位置:首页 > 其它

LeetCode Regular Expression Matching

2015-11-12 07:58 232 查看
Description:

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:

dp[i][j] represents whether s[0,i-1] and p[0,j-1] is a match.

We can have three situations s[i-1] and p[j-1]:

if p[j] != '.' and [j] != '*'
dp[i][j] = dp[i-1][j-1] + s[i-1] == p[j-1];
else if p[j] == '.'
dp[i][j] = dp[i-1][j-1];
else // p[j] = '*'
if (j>1)
if (dp[i][j-1] || dp[i][j-2])
dp[i][j] = true
else if(i>0 && dp[i-1][j] && (p[j-2]=='.' || s[i-1]==p[j-2] ) )  //(1)
dp[i][j] = true


(1) Because we may have the situation that "" and ".*" is a match, so we need to start i from 0.

<span style="font-size:18px;">public class Solution {
public boolean isMatch(String s, String p) {
if (s == null || p == null)
return false;

int n = s.length();
int m = p.length();

boolean dp[][] = new boolean[n + 1][m + 1];
dp[0][0] = true;

char ch1, ch2;
for (int i = 0; i <= n; i++) {
for (int j = 1; j <= m; j++) {
ch2 = p.charAt(j - 1);

if (ch2 == '*') {
if (j > 1) {
if (dp[i][j - 1] || dp[i][j - 2])
dp[i][j] = true;
else if (i > 0
&& (p.charAt(j - 2) == s.charAt(i - 1) || p
.charAt(j - 2) == '.') && dp[i - 1][j])
dp[i][j] = true;
}
} else if (i > 0) {
ch1 = s.charAt(i - 1);
if (ch2 == '.') {
dp[i][j] = dp[i - 1][j - 1];
} else {
if (ch1 == ch2)
dp[i][j] = dp[i - 1][j - 1];
}
}
}
}
return dp
[m];
}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: