網址
題目
字符串匹配,匹配串包含?
、*
兩個字符,前者可以匹配一個字符,後者可以匹配多個字符串(包括空值)
解法1 - 一般思路
- 很自然的思路,一個一個字符匹配,當遇到
*
特殊處理下
class Solution {
public boolean isMatch(String s, String p) {
int i = 0, j = 0; // location of pointer for s and p
int jstar = -1; // location of star in p
int imatchstar = -1; // location of star match in s
while(i < s.length()) {
if(j < p.length() && (p.charAt(j) == '?' || s.charAt(i) == p.charAt(j))){ //匹配
i++;
j++;
}else if(j < p.length() && p.charAt(j) == '*'){ //出現star,記錄star對應的位置
jstar = j;
imatchstar = i;
j++;
}else if(jstar != -1){ //不匹配但出現過star,pattern中star位置但後一位去匹配i的位置
j = jstar + 1;
imatchstar++;
i = imatchstar;
}else{
return false;
}
}
while(j < p.length() && p.charAt(j) == '*') j++;
return (j < p.length())?false:true;
}
}
解法2 - DP
- 看到討論區裏熱門的都用了dp,代碼如下:
public class Solution {
public boolean isMatch(String s, String p) {
if (s == null && p == null) return true;
if (s == null || p == null) return false;
// matched[i][j]表示是否成功匹配到p的第i個字符和s的第j個字符
boolean[][] matched = new boolean[p.length()+1][s.length()+1];
matched[0][0] = true;
for(int i=1; i<=p.length(); i++) {
matched[i][0] = (p.charAt(i-1) == '*' && matched[i-1][0]);
for(int j=1; j<=s.length(); j++) {
if (p.charAt(i-1) == '*') // i位置再匹配一個j or i位置匹配空值
matched[i][j] = matched[i][j-1] || matched[i-1][j];
else if (p.charAt(i-1) == '?' || p.charAt(i-1) == s.charAt(j-1))
matched[i][j] = matched[i-1][j-1];
}
}
return matched[p.length()][s.length()];
}
}