[leetcode]Regular Expression Matching

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 + 1][j + 1]表示字符串s(0~ i )和p(0~j)的匹配情况。

初始状态:dp[0][0] = true;

当s[i] == p[j] || p[j] == '.' 则dp[i][j] = dp[i - 1][j - 1]

当p[j] == '*'时:分两种情况:

1. s[i] != p[j - 2] && p[j - 2] != '.' 则dp[i][j] = dp[i][j - 2];

2. else dp[i][j] =  dp[i][j - 2] | dp[i - 1][j];

代码如下:

 1 public class Solution {
 2     public boolean isMatch(String s, String p) {
 3             int height = s.length(),width = p.length();
 4             boolean[][] dp = new boolean[height + 1][width + 1];
 5             dp[0][0] = true;
 6             for(int i = 1; i <= width; i++){
 7                 if(p.charAt(i - 1) == '*') dp[0][i] = dp[0][i - 2];
 8             }
 9             for(int i = 1; i <= height; i++){
10                 for(int j = 1; j <= width; j++){
11                     char sChar = s.charAt(i - 1);                
12                     char pChar = p.charAt(j - 1);
13                     if(sChar == pChar || pChar == '.'){
14                         dp[i][j] = dp[i - 1][j - 1];
15                     }else if(pChar == '*'){
16                         if(sChar != p.charAt(j - 2) && p.charAt(j - 2) != '.'){
17                             dp[i][j] = dp[i][j - 2];
18                         }else{
19                             dp[i][j] =  dp[i][j - 2] | dp[i - 1][j];
20                         }
21                     }
22                 }
23             }
24             return dp[height][width];
25         }
26 }

 

posted on 2014-08-08 16:37  喵星人与汪星人  阅读(368)  评论(0编辑  收藏  举报