題目:
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”) → true
題意:
實現字符串的正則匹配,’.’能夠匹配任意字符,’*’能夠代替0個或者多次它前面的字符。
思路:
使用回溯的方法,主要需要考慮的是’‘,如果當前字符的下一個字符是’ ‘的話,那麼當前字符可以匹配0次,或者1次或者多次。我們使用兩個下標i,j指向源串與目標串的下次需要匹配的位置。那麼當j+1指向的是’ * ‘的話,那麼我們可以匹配0次,即讓第二個指示器往後移動兩個到j+2,i不變。或者匹配一次,i往後移動一位,而j不變,這樣由於j後面的還是’ *’,所以還可以匹配j的0或者多次。
以上。
代碼如下:
class Solution {
public:
bool isMatch(string s, string p) {
this->s = s;
this->p = p;
sLen = s.length();
pLen = p.length();
return isMatch(0, 0);
}
bool isMatch(int i, int j) {
if (i == sLen && j == pLen)return true;
else if (j == pLen)return false;
else if (i > sLen) {
return false;
}
if (j != pLen - 1 && p[j + 1] == '*') {
bool result = isMatch(i, j + 2) || ((s[i] == p[j] || p[j] == '.') && isMatch(i + 1, j));
return result;
}
else if (s[i] == p[j] || p[j] == '.') {
return isMatch(i + 1, j + 1);
}
else return false;
}
private:
string s;
string p;
int sLen;
int pLen;
};