題設
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
要點
- 二維數組動態規劃DP[][]
首先,按照之前解回文串的思路,這種題可以考慮采用動態規劃的方法來做。我們用DP[i][j]表示s[0->(i-1)]與p[0->(j-1)]是否匹配。
如果s、p為null,返回false。注意這里不能s.length=0或p.length=0就返回false,因為""可以和".*"匹配的。
初始化DP[0][0]=true,代表s、p都為空串。然后進行初始化。初始化過程中運用到的遞推公式為:
DP[0][j-1] = true && p.charAt(j) = '*',則DP[0][j+1] = true。即前j-1個字符串可以形成空串,且第j個字符為'*'。則前j個字符串也可以形成空串。
DP[i][0]的初始化方法相同。
然后,考慮s、p都非空的情況。遞推公式有:
if(s.charAt(i) == p.charAt(j) || p.charAt(j) = '.'),即s的第i位與p的第j位可以匹配。
則如果s的前i-1位與p的前j-1位匹配,就有s的前i位與p的前j位匹配。即:DP[i+1][j+1] = DP[i][j]
if(p.charAt(j) == '*')如果P[j] = '*',那么需要繼續分情況討論。注意第一位不會是*,所以此時有j>=1
1、p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.'
這種情況下,x*只能轉化為空,才有可能匹配。匹配成立的條件是DP[i+1][j+1] = DP[i+1][j-1],x*轉化為空,往前挪2位;
2、p.charAt(j - 1) == s.charAt(i) || p.charAt(j - 1) == '.'
這種情況下,x*可以為空、可以為x、可以為≥2個x,分類討論:
2.1、x*為空。則與1相同,DP[i+1][j+1] = DP[i+1][j-1],x*轉化為空,往前挪2位;
2.2、x*=x,則DP[i+1][j+1] = DP[i+1][j];
2.3、x*=xx...x。這種情況下,如果s刪掉最后一位后匹配,則匹配(x*再補出最后一位即可)。有DP[i+1][j+1] = DP[i][j+1]。
代碼:
public static boolean isMatch(String s , String p){
if(s == null || p == null) // 注意s=""的時候,p=".*"這樣是可以匹配的!
return false;
boolean DP[][] = new boolean[s.length() + 1][p.length() + 1]; // DP[i][j]代表S[0,1,2,..,i-1]與P[0,1,2,...,j-1]是否匹配
DP[0][0] = true;
for(int j = 1;j < p.length();j++){
if(DP[0][j - 1] && p.charAt(j) == '*') // 遞推公式:P[0,j-1]可以為空,且P[j] = '*',則P[0 , j]可以為空
DP[0][j + 1] = true;
else
DP[0][j + 1] = false;
}
for(int i = 1;i < s.length();i++){
if(DP[i - 1][0] && s.charAt(i) == '*') // 同理
DP[i + 1][0] = true;
}
for(int i = 1;i <= s.length();i++){
for(int j = 1;j <= p.length();j++){
if(s.charAt(i - 1) == p.charAt(j - 1)){ // S[i-1]=P[j-1],則DP[i][j] = DP[i-1][j-1]
DP[i][j] = DP[i - 1][j - 1];
}
if(p.charAt(j - 1) == '.') // P[j-1]='.',匹配任何字符,則DP[i][j] = DP[i-1][j-1]
DP[i][j] = DP[i - 1][j - 1];
/*
如果P[j - 1] = '*',那么需要繼續分情況討論。注意第一位不會是*,所以此時有j>=2
1、如果P[j-2] != S[i-1]且P[j-2] != '.',則x*需要為0個,此時DP[i][j] = DP[i][j - 2]
2、如果P[j-2] == S[i-1]或P[j - 2] == '.',分3類討論:
2.1、x*為0個,則有DP[i][j] = DP[i][j - 2]
2.2、x*為1個,則有DP[i][j] = DP[i][j - 1]
2.3、x*為多個,這種情況下,如果s刪掉最后一位后匹配,則匹配(x*再補出最后一位即可)。即DP[i][j] = DP[i-1][j]
*/
if(p.charAt(j - 1) == '*'){
if(p.charAt(j - 2) != s.charAt(i - 1) && p.charAt(j - 2) != '.')
DP[i][j] = DP[i][j - 2];
else{
DP[i][j] = (DP[i][j - 2] || DP[i][j - 1] || DP[i - 1][j]);
}
}
}
}
for(int i = 0;i <= s.length();i++){
for(int j = 0;j < p.length();j++){
System.out.print(DP[i][j] + " ");
}
System.out.println();
}
System.out.println("--------------");
return DP[s.length()][p.length()];
}