LeetCode 10 Regular Expression Matching (Regular Expression Matching)
Translation
Supports regular expressions of "." and. "." Matching supports a single character "*" matching zero or multiple previous element matching should overwrite the entire input string (rather than local ). The prototype of this function should be: bool isMatch (const char * s, const char * p) Example: isMatch (aa, a) → falseisMatch (aa, aa) → trueisMatch (aaa, aa) → falseisMatch (aa, a *) → trueisMatch (aa ,. *) → trueisMatch (AB ,. *) → trueisMatch (aab, c * a * B) → true
Original
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) → falseisMatch(aa,aa) → trueisMatch(aaa,aa) → falseisMatch(aa, a*) → trueisMatch(aa, .*) → trueisMatch(ab, .*) → trueisMatch(aab, c*a*b) → true
C #, recursion
public class Solution{ public bool IsMatch(string s, string p) { if (p.Length == 0) return s.Length == 0; if (p.Length == 1) return (s.Length == 1) && (p[0] == s[0] || p[0] == '.'); if (p[1] != '*') { if (s.Length == 0) return false; else return (s[0] == p[0] || p[0] == '.') && IsMatch(s.Substring(1), p.Substring(1)); } else { while (s.Length > 0 && (p[0] == s[0] || p[0] == '.')) { if (IsMatch(s, p.Substring(2))) return true; s = s.Substring(1); } return IsMatch(s, p.Substring(2)); } }}