Created
July 6, 2017 20:54
-
-
Save jianminchen/5436be46499de42ae40db2a03bb04257 to your computer and use it in GitHub Desktop.
Leetcode 10 - regular expression match - simplify the code - Inspired by the code: https://gist.github.com/jianminchen/f49268519f416338bc4a08df5d30590e
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 StringMatching | |
{ | |
/// <summary> | |
/// Leetcode 10: Regular Expression Matching | |
/// </summary> | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var result = IsMatch("aa", "aa"); | |
} | |
public static bool IsMatch(string text, string pattern) | |
{ | |
if (text == null || pattern == null) | |
{ | |
return false; | |
} | |
if (pattern.Length == 0) | |
{ | |
return text.Length == 0; | |
} | |
var test_pattern = pattern[0]; //# | |
bool isStar = pattern.Length > 1 && pattern[1] == '*'; | |
bool firstCharMatching = text.Length > 0 && | |
(test_pattern == '.' || text[0] == test_pattern); | |
if (pattern.Length > 1 && isStar) | |
{ | |
return IsMatch(text, pattern.Substring(2)) || | |
(firstCharMatching &&IsMatch(text.Substring(1), pattern)); | |
} | |
else if (firstCharMatching) | |
{ | |
return IsMatch(text.Substring(1), pattern.Substring(1)); | |
} | |
else | |
{ | |
return false; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment