Simple JAVA solution using Stack


  • 0
    C
    public class Solution
    {
        public String decodeString(String s)
        {
            String finalString = "";
            
            if(null == s || s.isEmpty())
            {
                return finalString;
            }
            
            Stack<String> stack = new Stack<String>();
            
            for(int i = 0; i < s.length(); i++)
            {
                if(Character.isDigit(s.charAt(i)))
                {
                    String numString = "";
                    
                    while(i < s.length() && Character.isDigit(s.charAt(i)))
                    {
                        numString += Character.toString(s.charAt(i));
                        i++;
                    }
                    i--;
                    
                    stack.push(numString);
                }
                else if(s.charAt(i) == ']')
                {
                    String repString = "";
                    
                    while(!stack.peek().equals("["))
                    {
                        repString = stack.pop() + repString;    
                    }
                    
                    stack.pop();
                    
                    int count = Integer.parseInt(stack.pop());
                    
                    String newString = "";
                    
                    for(int j = 0; j < count; j++)
                    {
                        newString += repString;
                    }
                    
                    stack.push(newString);
                }
                else
                {
                    stack.push(Character.toString(s.charAt(i)));
                }
                
            }
            
            while(!stack.isEmpty())
            {
                finalString = stack.pop() + finalString;
            }
            
            return finalString;
        }
    }

Log in to reply
 

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