1218-2019-LEETCODE-44-ワイルドカードマッチング

そこバグは、変更の場合には*空の文字列に一致します。

package Solution;

import org.junit.Test;

/**
 * @author pdzz
 * @create 2019-12-28 10:23
 */
public class Solution {

    public static void main(String[] args) {

    }
    public boolean isMatch(String s, String p) {
        if (s.isEmpty() && (p.isEmpty() || p.equals("*"))){
            return true;
        }
        if (!p.isEmpty()){
            if ((p.charAt(0) == s.charAt(0)) || p.charAt(0) == '?'){
                return isMatch(s.substring(1),p.substring(1));
            }else if (p.charAt(0) == '*'){
                return isMatch(s.substring(1),p);
            }
        }
        return false;
    }

    @Test
    public void test1(){
        System.out.println(isMatch("abceb", "*a*b"));
    }
}

トピック出典:LEETCODEから
https://leetcode-cn.com/problems/wildcard-matching/

ダブルポインタソリューション出典ます。https://leetcode-cn.com/problems/wildcard-matching/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w -9 /
コードは以下の通りであります:

public boolean isMatch1(String str, String pattern){
        int s = 0, p = 0, match = 0, starIdx = -1;
        //遍历整个字符串
        while (s < str.length()){
            // 一对一匹配,两指针同时后移。
            if (p < pattern.length()  && (pattern.charAt(p) == '?' || str.charAt(s) == pattern.charAt(p))){
                s++;
                p++;
            }
            // 碰到 *,假设它匹配空串,并且用 startIdx 记录 * 的位置,记录当前字符串的位置,p 后移
            else if (p < pattern.length() && pattern.charAt(p) == '*'){
                starIdx = p;
                match = s;
                p++;
            }
            // 当前字符不匹配,并且也没有 *,回退
            // p 回到 * 的下一个位置
            // match 更新到下一个位置
            // s 回到更新后的 match
            // 这步代表用 * 匹配了一个字符
            else if (starIdx != -1){
                p = starIdx + 1;
                match++;
                s = match;
            }
            //字符不匹配,也没有 *,返回 false
            else return false;
        }

        //将末尾多余的 * 直接匹配空串 例如 text = ab, pattern = a*******
        while (p < pattern.length() && pattern.charAt(p) == '*')
            p++;

        return p == pattern.length();
    }
公開された98元の記事 ウォンの賞賛0 ビュー2212

おすすめ

転載: blog.csdn.net/weixin_43221993/article/details/103742168