[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;
		}

    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章