题解 | #字符串通配符#

字符串通配符

https://www.nowcoder.com/practice/43072d50a6eb44d2a6c816a283b02036

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String a = in.nextLine().toLowerCase();
            String b = in.nextLine().toLowerCase();
            //将连续的多个'*'替换成一个,防止超时
            System.out.println(isMatched(a.replaceAll("\\*+", "*"), b, 0, 0));
        }
    }

    public static boolean isMatched(String regex, String str, int p1, int p2) {
        if (p1 == regex.length() && p2 == str.length()) {
            return true;
        } else if (p1 == regex.length() || p2 == str.length()) {
            return false;
        }
        //字符为'*',并且,满足匹配规则的才可以进行匹配
        if (regex.charAt(p1) == '*' && isDigitAndLetter(str.charAt(p2))) {
            return isMatched(regex, str, p1, p2 + 1) ||
                   isMatched(regex, str, p1 + 1, p2 + 1) || isMatched(regex, str, p1 + 1, p2);
        } else if ((regex.charAt(p1) == '?' && isDigitAndLetter(str.charAt(p2))) ||
                   regex.charAt(p1) == str.charAt(p2)) {
            return isMatched(regex, str, p1 + 1, p2 + 1);
        } else {
            return false;
        }
    }

    public static boolean isDigitAndLetter(char chr) {
        return Character.isDigit(chr) || Character.isLetter(chr);
    }
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务