Untitled

 avatar
unknown
plain_text
2 months ago
1.5 kB
2
Indexable
class Solution {
    public String decodeString(String s) {
        Stack<Object> stack = new Stack<>(); // Single stack for both multipliers and strings
        StringBuilder currentString = new StringBuilder();
        int k = 0; // Current multiplier
        
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                // Build the multiplier (can have multiple digits)
                k = k * 10 + (c - '0');
            } else if (c == '[') {
                // Push the current multiplier and string onto the stack
                stack.push(currentString);
                stack.push(k);
                // Reset for the new scope
                currentString = new StringBuilder();
                k = 0;
            } else if (c == ']') {
                // Pop the multiplier and the previous string from the stack
                int multiplier = (int) stack.pop();
                StringBuilder previousString = (StringBuilder) stack.pop();
                // Repeat the current string and append it to the previous string
                for (int i = 0; i < multiplier; i++) {
                    previousString.append(currentString);
                }
                currentString = previousString;
            } else {
                // Append characters to the current string
                currentString.append(c);
            }
        }
        
        return currentString.toString();
    }
}
Editor is loading...
Leave a Comment