rambless

字符串通配符

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

import java.util.*;

// 注意类名必须为 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
            //除了*和?,如果不存在,则一定false
            String reg = in.nextLine().toLowerCase();
            String str = in.nextLine().toLowerCase();
            match(reg, str);
        }
    }

    private static void match(String reg, String str) {
        boolean[][] dp = new boolean[reg.length()+1][str.length()+1];
        //首列初始化
        dp[0][0] = true;
        for(int i=0; i<reg.length(); i++) {
            if(reg.charAt(i)=='*') {
                dp[i+1][0] = true;
            } else {
                break;
            }
        }
        //从第一列开始
        char r, s;
        for(int i=0; i<reg.length(); i++) {
            r = reg.charAt(i);
            for(int j=0; j<str.length(); j++) {
                s = str.charAt(j);
                //如果字符相同
                if(r==s) {
                    dp[i+1][j+1] = dp[i][j];
                }
                //如果是'?'
                if(r=='?' && (Character.isDigit(s) || (97<=s && s<=122))) {
                    dp[i+1][j+1] = dp[i][j];
                }
                //如果是'*'
                if(r=='*') {
                    dp[i+1][j+1] = dp[i+1][j] || dp[i][j+1] || dp[i][j];
                }
            }
        }
        System.out.println(dp[reg.length()][str.length()]);
    }
}

全部评论

相关推荐

2025-12-11 14:24
门头沟学院 Java
牛客35720396...:不要用boss,全是骗
点赞 评论 收藏
分享
2025-12-19 15:04
门头沟学院 Java
小肥罗:hr爱上你了,你负责吗哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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