394 Decode String

Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

Example:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

解釋下題目:

具體形式就是一個(gè)數(shù)字N加一個(gè)中括號(hào),然后輸出N次中括號(hào)里面的內(nèi)容,其本質(zhì)就是數(shù)學(xué)表達(dá)式求解的問題啦。

1. 堆棧

實(shí)際耗時(shí):1ms

public String decodeString(String s) {
    LinkedList<String> stack = new LinkedList<>();
    int num = 0;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c >= '0' && c <= '9') {
            num = num * 10 + c - '0';
        } else {
            if (num > 0) {
                stack.push(String.valueOf(num));
                num = 0;
            }
            if (c >= 'a' && c <= 'z') {
                stack.push(String.valueOf(c));
            } else if (c >= 'A' && c <= 'Z') {
                stack.push(String.valueOf(c));
            } else {
                // can only be '[' or ']'
                if (c == '[') {
                    stack.push(String.valueOf(c));
                } else {
                    // need to pop
                    StringBuilder tmp = new StringBuilder();
                    while (!stack.isEmpty()) {
                        String temp = stack.pop();
                        if (temp.equals("[")) {
                            break;
                        } else {
                            tmp.insert(0, temp);
                        }
                    }
                    String count = stack.pop();
                    stack.push(helper(count, tmp.toString()));
                }
            }
        }
    }
    StringBuilder res = new StringBuilder();
    while (!stack.isEmpty()) {
        res.append(stack.getLast());
        stack.removeLast();
    }
    return res.toString();
}

private String helper(String count, String s) {
    StringBuilder sb = new StringBuilder();
    try {
        for (int i = 0; i < Integer.valueOf(count); i++) {
            sb.append(s);
        }
    } catch (NumberFormatException c) {
        System.out.println(count);
    }

    return sb.toString();
}
踩過的坑:emmm其實(shí)是包含大小寫的....我一開始以為只有小寫,但是無傷大雅。

??思路與求數(shù)學(xué)表達(dá)式的值的思路一模一樣。

時(shí)間復(fù)雜度O(n)
空間復(fù)雜度O(n)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容