Java 4ms using Stack; StringBuilder


  • 0
    V
        public String decodeString(String s) 
        {
            Stack<StringBuilder> mySb = new Stack<StringBuilder>();
            Stack<Integer> myNum = new Stack<Integer>();
            char [] chArr = s.toCharArray();
            for(int i = 0; i < chArr.length; i++)
            {
                if(chArr[i] < 58 && chArr[i] > 47)
                {
                    int t = 0;
                    while(chArr[i] < 58 && chArr[i] > 47)
                    {
                        t *= 10;
                        t += (int)chArr[i] - 48;
                        i++;
                    }
                    i--;
                    myNum.push(t);   
                }
                else
                {
                    if(chArr[i] == ']')
                    {
                        StringBuilder temp = new StringBuilder();
                        while(!mySb.peek().toString().equals("["))
                            temp.append(mySb.pop());
                        mySb.pop();
                        int cnt = myNum.pop();
                        String str = temp.toString();
                        while(cnt-- > 1)
                            temp.append(str);
                        mySb.push(temp);
                    }
                    else
                        mySb.push(new StringBuilder(String.valueOf(chArr[i])));
                }
            }
            StringBuilder toRet = new StringBuilder();
            while(!mySb.isEmpty())
                toRet.append(mySb.pop());
            return toRet.reverse().toString();
        }

Log in to reply
 

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