Shopee 字符正则匹配

试题
判断两个字符串能否完全匹配的上
匹配任意字符一次 如 a?c abc
# 匹配任意字符0次或一次 如 a#c ac abc
* 匹配任意字符0次或无限次 如 a*c ac abc abbbbc

代码
过了96%,可能还有些边界。
这一题显然每次遇到匹配符的时候都有几种可能的组合形式,所以我们使用递归把每种情况的搜一下。

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str1 = in.nextLine();
        String str2 = in.nextLine();
        int len1 = str1.length();
        int len2 = str2.length();
        if(compare(str1, str2, 0, 0, len1, len2))
            System.out.print(1);
        else
            System.out.print(0);
    }
    public static boolean compare(String s1, String s2, int t1, int t2, int l1, int l2){
        //终止条件是两个字符串都遍历到了尾部
        if(l1 == t1 && l2 == t2){
            return true;
        }
        //匹配一个字符情况,这里要保证在s1为?时,t2必须也要小于l2,因为s2中需要有个字符跳过
        if(t1 < l1 && t2 < l2 && (s1.charAt(t1) == s2.charAt(t2) || s1.charAt(t1) == '?') ){
            if(compare(s1, s2, t1+1, t2+1, l1, l2)) return true;
        //同理t2<l2,这样就能保证调用compare时t1,t2不会超过字符串长度,我们的递归的终止条件就不用考虑其他情况。
        }else if(t1 < l1 && s1.charAt(t1) == '#'){
            if(compare(s1, s2, t1+1, t2, l1, l2)) return true;
            if(t2 < l2 && compare(s1, s2, t1+1, t2+1, l1, l2)) return true;
        }else if(t1 < l1 && s1.charAt(t1) == '*'){
            if(compare(s1, s2, t1+1, t2, l1, l2)) return true;
            int nxt = t2;
            //匹配任意多次的情况
            while(nxt < l2 && s2.charAt(t2) == s2.charAt(nxt)){
                if(compare(s1, s2, t1+1, nxt+1, l1, l2)) return true;
                nxt++;
            }
        }
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值