10. Regular Expression Matching
Problem
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") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → trueRelated Topics:
Dynamic Programming Backtracking String
Analysis
影响匹配的主要因素是 *:
当遇到
*时,判断p前一个字符与s当前字符:若相等,
p不变,接着判断s的下一个字符。若不等,
s不变,接着判断p的下一个字符。
没有遇到
*时,判断p当前字符与s当前字符:若相等,判断
p下一个字符与s下一个字符。若不等,返回
false。
因为遍历时, * 扩展的数量是不确定的,例如:aaas 和 a*as,通常不会一步到位,需要涉及到回溯。
方法一:递归。遇到 * 时,两种情况都有可能得出正确结果,用 || 关联。没有遇到 * 时,只需判断一种情况。
方法二:DP。建立二维数组,遍历的同时,记录之前所有的匹配情况,依据这些情报,来确定当前的状态。
Code
递归
Dynamic Programming
Last updated