題目描述
實現支持'.'和'*'的正則表達式匹配。
'.'匹配任意一個字母。
'*'匹配零個或者多個前面的元素。
匹配應該覆蓋整個輸入字符串,而不僅僅是一部分。
需要實現的函數是:bool isMatch(string s, string p)
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
樣例 1:
輸入:"aa","a"
輸出:false
解釋:
無法匹配
樣例 2:
輸入:"aa","a*"
輸出:true
解釋:
'*' 可以重複 a
題解
這題既是高頻題也是困難題,谷歌面試官不喜歡候選人一上來就秒掉題目,而更重視你一步步根據題目優化解法,最後得到最優解的解題思路和過程。所以刷題不能光背代碼,還需要了解背後的算法和數據結構。
和 Wildcard Matching 同樣模板的代碼。
使用了記憶化搜索(Memoization Search)
考點:
- 記憶化搜索|| dp
題解:
- 採用數組memo記錄各處字符匹配情況,dfs遞歸進行搜索,記憶化剪枝
- 當前p串中有* ,就有兩種選擇,然後* 可以不去匹配,直接用p串的下一個匹配當前s串字符,或者重複p串的上一個字符匹配。
- .可以匹配任意字符
public class Solution {
/**
* @param s: A string
* @param p: A string includes "." and "*"
* @return: A boolean
*/
public boolean isMatch(String s, String p) {
if (s == null || p == null) {
return false;
}
boolean[][] memo = new boolean[s.length()][p.length()]; //記憶搜索結果
boolean[][] visited = new boolean[s.length()][p.length()]; //標記是否訪問
return isMatchHelper(s, 0, p, 0, memo, visited);
}
private boolean isMatchHelper(String s, int sIndex,
String p, int pIndex,
boolean[][] memo,
boolean[][] visited) {
// "" == ""
if (pIndex == p.length()) { //如果p已經匹配完畢
return sIndex == s.length(); //根據s是否匹配完畢即可
}
if (sIndex == s.length()) { //如果s匹配完畢
return isEmpty(p, pIndex);
}
if (visited[sIndex][pIndex]) {
return memo[sIndex][pIndex];
}
char sChar = s.charAt(sIndex);
char pChar = p.charAt(pIndex);
boolean match;
// consider a* as a bundle
if (pIndex + 1 < p.length() && p.charAt(pIndex + 1) == '*') { //如果爲'*',有兩種方案
match = isMatchHelper(s, sIndex, p, pIndex + 2, memo, visited) || //'*'不去匹配字符
charMatch(sChar, pChar) && isMatchHelper(s, sIndex + 1, p, pIndex, memo, visited); //'*'重複前面一個字符去匹配s
} else {
match = charMatch(sChar, pChar) && //如果當前兩字符匹配
isMatchHelper(s, sIndex + 1, p, pIndex + 1, memo, visited); //繼續下一個字符匹配
}
visited[sIndex][pIndex] = true; //搜索完成就標記
memo[sIndex][pIndex] = match; //存儲搜索結果
return match;
}
private boolean charMatch(char sChar, char pChar) { //判斷兩字符是否匹配
return sChar == pChar || pChar == '.';
}
private boolean isEmpty(String p, int pIndex) { //形如"x*x*"形式
for (int i = pIndex; i < p.length(); i += 2) {
if (i + 1 >= p.length() || p.charAt(i + 1) != '*') { //如果不是'*',無法匹配
return false;
}
}
return true;
}
}