字符串匹配
矩阵类的题目能用DFS解答的都要想到memoization来优化,Tree则不能用memo优化
Wildcard Matching
class Solution {
/*
"abcab" and "*a*b"
p is allStar "***"
isMatch(s, sIndex, p, pIndex)
pIndex == sIndex -> return isMatch(s, sIndex + 1, p, pIndex + 1)
pIndex == ? -> return isMatch(s, sIndex + 1, p, pIndex + 1)
group into same isCharMatch(sChar, pChar)
pIndex == * -> return isMatch(s, sIndex, p, pIndex + 1) || isMatch(s, sIndex + 1, p, pIndex)
use memoization to avoid duplicate calculation
boolean[m][n] visited
boolean[m][n] memo
O(m * n) Time
O(m * n) Space
*/
public boolean isMatch(String s, String p) {
if (s == null || p == null) return false;
int m = s.length(), n = p.length();
//use memoization to avoid duplicate calculation
boolean[][] visited = new boolean[m][n];
boolean[][] memo = new boolean[m][n];
return isMatch(s, 0, p, 0, visited, memo);
}
//definition of recursion: check whether s.substring(sIndex) and p.substring(pIndex) can be a match or not
private boolean isMatch(String s, int sIndex, String p, int pIndex, boolean[][] visited, boolean[][] memo) {
//base case
if (pIndex == p.length()) {
return sIndex == s.length() ;
}
if (sIndex == s.length()) {
return isAllStar(p, pIndex);
}
//fetch from memo
if (visited[sIndex][pIndex]) {
return memo[sIndex][pIndex];
}
//transition
char sChar = s.charAt(sIndex), pChar = p.charAt(pIndex);
if (pChar == '*') {
memo[sIndex][pIndex] = isMatch(s, sIndex, p, pIndex + 1, visited, memo) || isMatch(s, sIndex + 1, p, pIndex, visited, memo);
} else {
memo[sIndex][pIndex] = isCharMatch(sChar, pChar) && isMatch(s, sIndex + 1, p, pIndex + 1, visited, memo);
}
//set memo
visited[sIndex][pIndex] = true;
return memo[sIndex][pIndex];
}
private boolean isAllStar(String p, int idx) {
for (int i = idx; i < p.length(); i++) {
if (p.charAt(i) != '*') {
return false;
}
}
return true;
}
private boolean isCharMatch(char sChar, char pChar) {
return sChar == pChar || pChar == '?';
}
}Regular Expression Matching
Word Break
Word Break II
Last updated