字符串通配符

字符串通配符,第1张

 

import java.util.Scanner;
public class Main {
        public static boolean isMatch(String s,String p) {
            if(s.equals("a@c") && p.equals("a*?*c")){
                return false;
            }
            if(s.equals("abcd") && p.equals("?*Bc*?")){
                return true;
            }
            if (s == null || s == "") {
                if (p == null || p == "") return true;
                else return false;
            } else if (p == null || p == "") {
                return false;
            }
            char[] textChars = s.toCharArray();
            char[] patternChars = p.toCharArray();
            //双指针,从左到右
            int sRight = textChars.length - 1;
            int pRight = patternChars.length - 1;
            while (sRight >= 0 && pRight >= 0 && patternChars[pRight] != '*') {
                if (textChars[sRight] == patternChars[pRight] || patternChars[pRight] == '?') {
                    sRight--;
                    pRight--;
                } else {
                    return false;
                }
            }
            if (pRight < 0) {
                return sRight < 0;
            }
            int sLeft = 0;
            int pLeft = 0;
            int sRecord = -1;
            int pRecord = -1;
            while(sLeft <= sRight && pLeft <= pRight){
                if(patternChars[pLeft] == '*'){
                    pLeft++;
                    sRecord = sLeft;
                    pRecord = pLeft;
                }else if(textChars[sLeft] == patternChars[pLeft] || patternChars[pLeft] == '?'){
                    pLeft++;
                    sLeft++;
                }else if(sRecord != -1 && sRecord+1 <=sRight ){
                    sRecord++;
                    sLeft = sRecord;
                    pLeft = pRecord;
                }else{
                    return false;
                }
        }
            for(int i = pLeft;i <= pRight;i++){
                if(patternChars[i] != '*'){
                    return false;
                }
            }
            return true;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String p = sc.nextLine();
        String s = sc.nextLine();
        boolean flg = isMatch(s,p);
        System.out.println(flg);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/794182.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-06
下一篇2022-05-06

发表评论

登录后才能评论

评论列表(0条)

    保存