leetcode44-通配符匹配
- dp
和正则匹配方法类似。先去处理边界值为0的情况。dp[0][0] = true,同时让j从0到n开始遍历,如果当前的位置是,那么dp[0][j] = true,因为可以匹配0个字符,否则表明无法继续零匹配,直接跳出循环。
然后进行二维循环,如果当前的匹配串为*,那么有两种选择,匹配之前的字符或者零匹配。如果当前的字符为?,那么可以进行一次匹配,否则,需要看匹配串和原字符串的字符是否相等,且依赖于dp[i-1][j-1]的状态
class Solution {
    public boolean isMatch(String s, String p) {
        int m = s.length(), n = p.length();
        boolean dp[][] = new boolean[m+1][n+1];
        dp[0][0] = true;
        for(int j = 1; j <= n; j++){
            if(p.charAt(j-1) == '*')    dp[0][j] = true;
            else    break;
        }
        for(int i = 1; i <= m; i++){
            for(int j = 1; j <= n; j++){
                if(p.charAt(j-1) == '*')    dp[i][j] = dp[i-1][j] || dp[i][j-1];
                else    dp[i][j] = dp[i-1][j-1] && (p.charAt(j-1) == '?' || s.charAt(i-1) == p.charAt(j-1));
            }
        }
        return dp[m][n];
    }
}
- 贪心
class Solution {
    public boolean isMatch(String s, String p) {
        int sRight = s.length(), pRight = p.length();
        while (sRight > 0 && pRight > 0 && p.charAt(pRight - 1) != '*') {
            if (charMatch(s.charAt(sRight - 1), p.charAt(pRight - 1))) {
                --sRight;
                --pRight;
            } else {
                return false;
            }
        }
        if (pRight == 0) {
            return sRight == 0;
        }
        int sIndex = 0, pIndex = 0;
        int sRecord = -1, pRecord = -1;
        
        while (sIndex < sRight && pIndex < pRight) {
            //如果p当前位置是*,那么跳过这个字符,进行标记,继续匹配
            if (p.charAt(pIndex) == '*') {
                ++pIndex;
                sRecord = sIndex;
                pRecord = pIndex;
            } else if (charMatch(s.charAt(sIndex), p.charAt(pIndex))) { //如果能匹配,继续进行
                ++sIndex;
                ++pIndex;
            } else if (sRecord != -1 && sRecord + 1 < sRight) { //如果匹配不了并且这个字符不是p的最后一个字符(最后一个字符可以用sRight的*来匹配),那么寻找下一个*起始的位置(之前用sRecord标记
                ++sRecord;
                sIndex = sRecord;
                pIndex = pRecord;
            } else {
                return false;
            }
        }
        return allStars(p, pIndex, pRight);
    }
    public boolean allStars(String str, int left, int right) {
        for (int i = left; i < right; ++i) {
            if (str.charAt(i) != '*') {
                return false;
            }
        }
        return true;
    }
    public boolean charMatch(char u, char v) {
        return u == v || v == '?';
    }
}
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号