[LeetCode] Regular Expression Matching

这个问题比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;
		}

    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值