返回顶部

深信服24届秋招笔试复刻:2道hard题

正则表达式匹配

public class Main {
    public static void main(String[] args) {
        String s = "abccada";
        String p = "a.*a";
        System.out.println(isMatch(s, p));
    }
    static boolean matches(String s, String p, int i, int j){
        if(i == 0) return false;
        if(p.charAt(j - 1) == '.') return true;
        return s.charAt(i - 1) == p.charAt(j - 1);
    }
    static boolean isMatch(String s, String p) {
        int sn = s.length(), pn = p.length();
        boolean [][] f = new boolean[sn + 1][pn + 1];
        f[0][0] = true;
        for(int i = 0; i <= sn; ++i){
            for(int j = 1; j <= pn; ++j){
                if(p.charAt(j - 1) == '*'){
                    f[i][j] = f[i][j - 2];
                    if(matches(s, p, i, j - 1)){
                        f[i][j] = f[i][j] || f[i - 1][j];
                    }
                } else if(matches(s, p, i, j)){
                    f[i][j] = f[i - 1][j - 1];
                }
            }
        }
        return f[sn][pn];
    }
}

所有可能的出栈顺序

public class Main {
    public static void main(String[] args) {
        //echo();
        String s = "abcdef";
        char [] seq = s.toCharArray();
        boolean [] visited = new boolean[seq.length];
        List<Character> res = new ArrayList<>();
        List<List<Character>> ans = new LinkedList<>();
        Stack<Character> stk = new Stack<>();
        bt(seq, visited, res, ans, stk);
        for (List<Character> cs : ans){
            for(char c : cs){
                System.out.print(c);
            } System.out.println();
        }

    }
    static void bt(char [] seq, boolean [] visited, List<Character> res, List<List<Character>> ans, Stack<Character> stk){
        if(res.size() == seq.length){
            // 在这里验证 是否是可行出栈顺序
            for(int i = 0, j = 0; i < seq.length; i++){
                stk.push(seq[i]);
                while(!stk.isEmpty() && stk.peek() == res.get(j)){
                    stk.pop();
                    j++;
                }
            }
            if(stk.isEmpty())
                ans.add(new ArrayList<>(res));
            stk.clear();
            return;
        }
        for(int i = 0; i < seq.length; i++){
            if(visited[i]) continue;
            visited[i] = false;
            res.add(seq[i]);
            bt(seq, visited, res, ans, stk);
            visited[i] = false;
            res.remove(res.size() - 1);
        }
    }
}
posted @ 2023-09-21 09:23  你好,一多  阅读(47)  评论(0编辑  收藏  举报