Created
July 6, 2017 19:14
-
-
Save jianminchen/f49268519f416338bc4a08df5d30590e to your computer and use it in GitHub Desktop.
Leetcode 10 - regular expression match - recursive solution - Very clear and simple recursive solution
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 Leetcode10_regularExpressionMatch_recursive | |
{ | |
/// <summary> | |
/// July 6, 2017 | |
/// Study recursive solution | |
/// code reference: | |
/// https://discuss.leetcode.com/topic/6183/my-concise-recursive-and-dp-solutions-with-full-explanation-in-c | |
/// </summary> | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
} | |
public bool IsMatch(string s, string p) | |
{ | |
if (p.Length == 0) | |
{ | |
return s.Length == 0; | |
} | |
if (p.Length >= 2 && '*' == p[1]) | |
{ | |
// x* matches empty string or at least one character: x* -> xx* | |
// *s is to ensure s is non-empty | |
return (IsMatch(s, p.Substring(2)) || | |
((s.Length > 0) && | |
(s[0] == p[0] || '.' == p[0]) && | |
IsMatch(s.Substring(1), p))); | |
} | |
else | |
{ | |
return (s.Length > 0) && | |
(s[0] == p[0] || '.' == p[0]) && | |
IsMatch(s.Substring(1), p.Substring(1)); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment