Decode String

题目地址:
https://leetcode.com/problems/decode-string/#/description

题目:
Given an encoded string, return it's 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].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
解题思路:
这道题就是用两个stack来解决问题,一个来存乘的数字,一个是char。如果是[,那么push数字,如果是],那将char乘以数字;如果是char的话更新char,最后else的话将char push进去。

代码:

public String decodeString(String s) {
    // Stack is deprecated so using double-ended Q    Deque<Integer> multipliers = new ArrayDeque<>();
    Deque<StringBuilder> result = new ArrayDeque<>();
    result.push(new StringBuilder());
    int multiplier = 0;

    // Would be nice to use an 'enhanced' for loop, but don't want    // the expense of converting the String to an array (ie toCharArray)    // for (char ch : s.toCharArray()) {    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        if (Character.isDigit(ch)) {
            multiplier = multiplier * 10 + ch - '0';
        }
        else if (ch == '[') {
            multipliers.push(multiplier);
            result.push(new StringBuilder());
            multiplier = 0; //reset        }
        else if (ch == ']') {
            StringBuilder str2Multiply = result.pop();
            int times = multipliers.pop();
            StringBuilder multipliedStr = new StringBuilder();
            for (int j = 0; j < times; j += 1) {
                multipliedStr.append(str2Multiply);
            }
            result.push(result.pop().append(multipliedStr));
        }
        else {
            result.push(result.pop().append(ch));
        }
    }

    return result.pop().toString();
}




Comments

Popular Posts