java实战字符串+栈5:解码字符


题目:

有形如 (重复字符串)<重复次数n> 的片段,解码后相当于n个重复字符串连续拼接在一起,求展开后的字符串。

 求解:

public static String zipString(String str) {
        if (str == null || str.length() == 0) {
            return "";
        }
        Stack sta = new Stack<>();
        str = str.replaceAll("<", "").replaceAll(">", ""); // 将<>全部替换掉
        for (int i = 0; i < str.length(); i++) {
            char cha = str.charAt(i);
            if (!(cha <= '9' && cha >= '1')) {
                sta.push("" + cha);
            } else {
                int tem = cha - '0'; // char型转整形
                Stack stack = new Stack<>(); // 建立一个临时栈,存储每个小括号中的元素
                while (true) {
                    String sss = sta.pop();
                    if (sss.equals(")")) {
                        continue;
                    } else if (sss.equals("(")) {
                        break;
                    } else {
                        stack.push(sss);
                    }
                }
                for (int k = 0; k < tem; k++) { // 遇到数字,前面必然有一个括号,
                    Stack newSta = (Stack) stack.clone(); // 注意拷贝一个栈给另一个栈,不能直接用stackA=stackB
                    while (!newSta.isEmpty()) {
                        sta.push(newSta.pop());
                    }
                }
            }
        }
        StringBuffer bf = new StringBuffer();
        while (!sta.isEmpty()) {
            String strTem = sta.pop();
            if (!strTem.equals("(") && !strTem.equals(")")) {
                bf.append(strTem);
            }
        }
        return bf.reverse().toString(); // 出栈的元素是相反的,需要转换一次
    }