题解 | #字符串通配符#

字符串通配符

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

import java.util.Scanner;

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
            String a = in.nextLine();
            String b = in.nextLine();
            Character c1 = '*';
            Character c2 = '?';
            a = a.toLowerCase();
            b = b.toLowerCase();
		  //去除多余的*,提高性能
            int count = 0;
            char[] ca = a.toCharArray();
            for (int i = 0;i + count < ca.length;i++){
                while (i + count < ca.length-1 && ca[i] == ca[i+count+1] && ca[i] == '*'){
                    count++;
                }
                ca[i] = ca[i+count];
            }
            a = new String(ca,0, ca.length - count);
            System.out.println(match(a, b));
        }
    }

    private static boolean match (String s1, String s2) {
	  //一系列递归出口
        if ("*".equals(s1) && (s2 == null || s2.length() == 0)){
            return true;
        }
        if ((s1 == null || s1.length() == 0 ) && (s2 == null || s2.length() == 0) ) {
            return true;
        }
        if ((s1 != null || s1.length() != 0 ) && (s2 == null || s2.length() == 0) ) {
            return false;
        }
        if ((s1 == null || s1.length() == 0 ) && (s2 != null || s2.length() != 0) ) {
            return false;
        }
        if (("?".equals(s1) && (
                    (s2.charAt(0) >= 'a' && s2.charAt(0) <= 'z')
                    || (s2.charAt(0) >= '0' && s2.charAt(0) <= '9')
                )) && s2.length() == 1) {
            return true;
        }

	  //分为两种,一个是算上*,匹配字符从第二个开始,一个是认为*没有匹配,当然要考虑题目里匹配的限制
        if ('*' == s1.charAt(0)) {
            return ( (
                    (s2.charAt(0) >= 'a' && s2.charAt(0) <= 'z')
                    || (s2.charAt(0) >= '0' && s2.charAt(0) <= '9')
                ) && match(s1, s2.substring(1)))
                || match(s1.substring(1), s2)
                ;          
        }

        if (s1.charAt(0) == s2.charAt(0)
                || ('?' == s1.charAt(0)
                    && (
                        (s2.charAt(0) >= 'a' && s2.charAt(0) <= 'z')
                        || (s2.charAt(0) >= '0' && s2.charAt(0) <= '9')
                    )
                   )) {
            return match(s1.substring(1), s2.substring(1));
        }
        return false;
    }
}

全部评论

相关推荐

大专境巅峰电子狗:头一次看到这种简历,学术与技术学习,直接用技能概括就好了呀,实习经历要写丰富一点
点赞 评论 收藏
分享
10-10 01:10
已编辑
深圳大学 测试开发
面了100年面试不知...:六月到九月,四个项目一个实习,是魔丸吗
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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