题解 | #字符串通配符#

字符串通配符

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);
        String pattern = in.nextLine();
        String str = in.nextLine();
        int[][] dpl = new int[pattern.length()+1][str.length()+1];
        dpl[0][0] = 1;
        //动态规划 dpl[i][j]的值与dpl[i-1][j-1] dpl[i][j-1] 和 dpl[i-1][j] 有关
        for(int i=1;i<dpl.length;i++){
            for(int j=0;j<dpl[0].length;j++){
                char cp = pattern.charAt(i-1);
                if(j==0){
                    if(cp=='*'&&dpl[i-1][j]==1){
                        dpl[i][j]=1;
                    }
                    continue;
                }
                char cs = str.charAt(j-1);
                if(dpl[i-1][j-1]==1){
                    if(match(cp,cs)||equal(cp,cs)){
                        dpl[i][j] = 1;
                        continue;
                    }else if(cp==cs){
                        dpl[i][j] = 1;
                        continue;
                    }
                }
                if(dpl[i][j-1]==1 && match(cp,cs)){
                    dpl[i][j] = 1;
                    continue;
                }
                if(dpl[i-1][j]==1 && match(cp,cs)){
                    dpl[i][j] = 1;
                    continue;
                }
            }
        }
        int res = dpl[pattern.length()][str.length()];
        System.out.println(res==1);
    }
    // 判断是否满足通配符通配格式,仅仅第一行为*和?不能说明匹配,还要验证"字符仅由英文字母和数字0到9组成"
    public static boolean match(char p,char c){
        if((p=='*' || p == '?')&&
           (
               (c>='0'&&c<='9')||
               (c>='a'&&c<='z')||
               (c>='A'&&c<='Z')
           )
          ){
            return true;
        }else{
            return false;
        }
    }
    // 判断字符与匹配字符是否相等,要求无视大小写
    public static boolean equal(char p,char c){
        if(p==c){
            return true;
        }else if(p>='a'&&p<='z' && c>='A'&&c<='Z' && (p-32)==c){
            return true;
        }else if(c>='a'&&c<='z' && p>='A'&&p<='Z' && (c-32)==p){
            return true;
        }
        return false;
    }
}


全部评论

相关推荐

不愿透露姓名的神秘牛友
06-18 16:32
quench@0916:一顿操作猛如虎,一看工资2500
点赞 评论 收藏
分享
后来123321:别着急,我学院本大二,投了1100份,两个面试,其中一个还是我去线下招聘会投的简历,有时候这东西也得看运气
点赞 评论 收藏
分享
评论
1
2
分享

创作者周榜

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