Stack simple solution


  • 0
    T

    public class Solution {

    public string DecodeString(string s) {
        Stack<string> stack = new Stack<string>();
        Stack<int> repeatStack = new Stack<int>();
        
        int n = 0;
        stack.Push("");
        foreach(char c in s){
            
            if(c == '['){
                repeatStack.Push(n);
                n = 0;
                stack.Push("");
            }else if(c == ']'){
                StringBuilder sb = new StringBuilder();
                string baseStr = stack.Pop();
                
                int repeatTimes = repeatStack.Pop();
                
                for(int i = 0;i<repeatTimes;i++){
                    sb.Append(baseStr);
                }
                
                stack.Push(stack.Pop()+sb.ToString());
                
            }else if(c >='0' && c <= '9'){
                n = n * 10 + (c-'0');
            }else{
                stack.Push(stack.Pop()+c);
            }
        }
        
        return stack.Pop();
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.