Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/f49268519f416338bc4a08df5d30590e to your computer and use it in GitHub Desktop.
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
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