题解 | #字符串通配符#

字符串通配符

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

/**
 * 枚举,加字符串查找
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        String a, b;
        try {
            a = r.readLine();
            b = r.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        char[] chs1 = new char[202];
        char[] chs2 = new char[202];
        a.getChars(0, a.length(), chs1, 0);
        b.getChars(0, b.length(), chs2, 0);
        System.out.print(isMatch(chs1, chs2, b.length()));
    }

    public static boolean isMatch(char[] chs1, char[] chs2, int l) {
        int i = 0, j = 0, tempi = 0, tempj = 0, flag = 0;
        while (j < l) {
            chs1[i] = Character.toUpperCase(chs1[i]);
            chs2[j] = Character.toUpperCase(chs2[j]);
            if (chs1[i] == '*') {
                tempi = i;
                i++;
                flag = 1;
                tempj = j;//先假设*匹配0个字符
            } else if (chs1[i] == chs2[j] || chs1[i] == '?' &&
                       isLegal(chs2[j])) {//i和j匹配,则均后移
                i++;
                j++;
            } else if (flag == 1) {//通配符前面出现过*
                j = tempj + 1;//*匹配的字符加1
                i = tempi;//i回到*位置
            } else return false;
        }
        while (chs1[i] == '*') {
            i++;
        }
        return chs1[i] == '\u0000';
    }

    public static boolean isLegal(char c) {
        return (c - 'A' | 'Z' - c) > 0 || (c - '0' | '9' - c) > 0;
    }
}


全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务