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
- 題目大意
實(shí)現(xiàn)一個(gè)判斷正則匹配的函數(shù)isMatch(s,p). 這個(gè)函數(shù)的第一個(gè)參數(shù)是要匹配的字符串s,第二個(gè)參數(shù)是正則表達(dá)式。
規(guī)則如下:
'.' 可以用來匹配人以單個(gè)字符
‘*’ 可以用來匹配0個(gè)或者多個(gè)上一個(gè)字符。
除了使用效率較低的搜索算法,我們發(fā)現(xiàn)對于任意一個(gè)字符串,前n個(gè)字符的匹配 和后面的字符沒有關(guān)系。所以我們可以用動(dòng)態(tài)規(guī)劃解這道題。 用match[i][j] 表示 字符串前i個(gè)字符 能否匹配 正則表達(dá)式前j個(gè)字符。
分情況討論:
match[i][j]=match[i-j][j-1] p[j]==s[i]
match[i][j]=match[i-j][j-1] p[j]!=s[i] && p[j]=='.'
match[i][j] = (match[i][j-1] || match[i-1][j] || match[i][j-2]) p[j]!=s[i] && p[j]=='*' && ( p[j-1]==s[i] || p[j-1]=='.')
match[i][j] = match[i][j-2] p[j]!=s[i] && p[j]=='*' && ( p[j-1]!=s[i] && p[j-1]!='.')
前1、2、4情況都很好理解,下面舉例說明第3種情況。
s: XXXXXXa
p: XXXXa*
s字符串的a 的位置是i, p字符串*的位置是j。
當(dāng)* 代表一個(gè)a 的時(shí)候 :match[i][j-1]
當(dāng)* 代表多個(gè)a的時(shí)候 :match[i-1][j]
當(dāng)* 代表空字符串的時(shí)候 :match[i][j-2]
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s,p) {
let match=new Array(s.length+1);
for (let i=0;i<=s.length;i++){
let temp=new Array(p.length+1);
temp.fill(false);
match[i]=temp;
}
match[0][0] = true;
for (let i = 0; i < p.length; i++) {
match[0][i+1] = (p[i] == '*' && match[0][i-1]);
}
for (let i = 0 ; i < s.length; i++) {
for (let j = 0; j < p.length; j++) {
if (p[j] == '.') {
match[i+1][j+1] = match[i][j];
}
if (p[j] == s[i]) {
match[i+1][j+1] = match[i][j];
}
if (p[j] == '*') {
if (p[j-1] != s[i] && p[j-1] != '.') {
match[i+1][j+1] = match[i+1][j-1];
} else {
match[i+1][j+1] = (match[i+1][j] || match[i][j+1] || match[i+1][j-1]);
}
}
}
}
return match[s.length][p.length];
};