这个问题比atoi还麻烦,开始自己造轮子了。首先是从左往右扫描还是从右往左扫描的问题,结果发现都不行,看来要两边都考虑,只能上递归了。然后遇到的问题是没有考虑x*可以一个字符都不匹配的问题。最后是一些边界上的问题,比如要匹配的字符串为空或者正则表达式为空的情况。由于要看下一个字符是不是“*”,所以我判断正则表达式的长度应该是需要的。总之搞了好多递归,终于Accept了所有的测试用例。不过代码我自己的代码已经看不太懂了,改来改去,原来的初衷都有些记不清了。
class Solution {
public:
bool isMatch(const char *s, const char *p) {
string input(s);
string reg(p);
int input_length = input.size();
int reg_length = reg.length();
if (reg_length == 0) { // reg is empty
return (input_length == 0 ? true : false);
}
else if (reg_length == 1 || (reg_length >= 2 && reg[1] != '*')) { // match the first char
if (reg[0] == input[0] || (reg[0] == '.' && input_length != 0)) {
return isMatch(s + 1, p + 1);
}
else{
return false;
}
}
else if (reg_length == 1 || (reg_length >= 2 && reg[reg_length - 1] != '*')) { // match the last char
if (reg[reg_length - 1] == input[input_length - 1] || (reg[reg_length - 1] == '.' && input_length != 0)) {
return isMatch(input.substr(0, input_length - 1).c_str(), reg.substr(0, reg_length - 1).c_str());
}
else {
return false;
}
}
else if (reg[1] == '*') { // match x*
string nextReg = reg.substr(2, reg_length - 2);
if (isMatch(s, nextReg.c_str())) { // skip x*
return true;
}
else {
int index = 1;
while (index <= input_length) {
if (input[index - 1] == reg[0] || reg[0] == '.') {
string m = input.substr(index - 1, input_length - (index - 1));
if (isMatch(m.c_str(), nextReg.c_str())) { // only match one x in the input, and skip x*
return true;
}
++index;
}
else {
break;
}
}
if (index < input_length || reg_length != 2) { // match next
string x = input.substr(index - 1, input_length - (index - 1));
return isMatch(x.c_str(), nextReg.c_str());
}
else {
return (index - 1) == input_length ? true : false;
}
}
}
else {
return false;
}
}
};