Solution in JAVA using single stack


  • 0
    B

    public String decodeString(String s) {

        Stack<Character> st = new Stack<Character>();
        
        for(char c : s.toCharArray() )
        {   
            String ss= ""; 
            String tt= ""; 
            if(Character.isDigit(c))
            st.push(c);
            else if(Character.isLetter(c))
            st.push(c);
            else if (c == ']')
            {
                while (!st.isEmpty() && st.peek() !='[' && Character.isLetter(st.peek()))
                {
                    ss = st.pop() + ss;
                
                }
                
                st.pop();
                
                while (!st.isEmpty()  && Character.isDigit(st.peek()))
                {
                    tt = st.pop() + tt;
                
                }
                
                int times = Integer.valueOf(tt);
                
             
                
                while(times > 0)
                {
                    for(char cc : ss.toCharArray() )
                    st.push(cc);
                    
                    times--;
                }
                
                
                
            }else
            {
                st.push(c);
                
            }
            
            
        }
        
        String x="";
        
            while(!st.isEmpty())
            {
                
                 x = st.pop() + x ;
                
            }
        
        return x;
        
    }

Log in to reply
 

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