Created
June 20, 2017 18:58
-
-
Save jianminchen/b9c5c6d9a696b54565cf115f2f3cca6d to your computer and use it in GitHub Desktop.
Leetcode 44 - regular expression match - study code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace RegularExpressionMatch | |
{ | |
/// <summary> | |
/// Leetcode 44 - regular expression match | |
/// | |
/// </summary> | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
} | |
public class Solution | |
{ | |
/// <summary> | |
/// study code - dynamic programming solution | |
/// </summary> | |
/// <param name="s"></param> | |
/// <param name="p"></param> | |
/// <returns></returns> | |
public bool isMatch(String s, String p) { | |
var match = new bool[s.Length + 1][]; | |
int length = s.Length; | |
int lengthP = p.Length; | |
for (int i = 0; i < length + 1; i++) | |
{ | |
match[i] = new bool[lengthP + 1]; | |
} | |
match[length][lengthP] = true; | |
// backward checking | |
for (int i = lengthP - 1; i >= 0; i--) | |
{ | |
if (p[i] != '*') | |
{ | |
break; | |
} | |
else | |
{ | |
match[length][i] = true; | |
} | |
} | |
// backward checking | |
for(int i = length - 1; i >= 0 ; i--){ | |
for (int j = lengthP - 1; j >= 0; j--) | |
{ | |
if (s[i] == p[j] || p[j] == '?') | |
{ | |
// one one match - for example, "abc","?bc" | |
match[i][j] = match[i + 1][j + 1]; | |
} | |
else if (p[j] == '*') | |
{ | |
// explain using your own words | |
// match[i + 1][j], s[i] matchs ?, s[i] cannot be ignored | |
// match[i][j+1], * does not match anything | |
match[i][j] = match[i + 1][j] || match[i][j + 1]; | |
} | |
else | |
{ | |
match[i][j] = false; | |
} | |
} | |
} | |
return match[0][0]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment