Java Stack Easy Solution


  • 0
    Z

    public class Solution {

    public boolean isDigit(char c) {
        return c >= '0' && c <= '9';
    }
    
    public boolean isAlpha(char c) {
        return c >= 'a' && c <= 'z';
    }
    
    public String decodeString(String s) {
        Stack<Integer> counts = new Stack<>();
        Stack<String> strs = new Stack<>();
        
        int cur = 0, n = s.length(), right;
        
        while(cur < n) {
            if(s.charAt(cur) == '[') {
                cur++;
            } else if(s.charAt(cur) == ']') {
                String str = strs.pop();
                int count = counts.pop();
                
                StringBuilder builder = new StringBuilder();
                
                while(count-- > 0) {
                    builder.append(str);
                }
                
                if(!strs.isEmpty()) {
                    builder.insert(0 , strs.pop());
                }
                
                strs.push(builder.toString());
                cur++;
            } else if(isDigit(s.charAt(cur))) {
                right = cur;
                while(right < n && isDigit(s.charAt(right)))
                    right++;
                int num = Integer.parseInt(s.substring(cur , right));
                
                counts.push(num);
                cur = right;
            } else {
                right = cur;
                while(right < n && isAlpha(s.charAt(right)))
                    right++;
                String str = s.substring(cur , right);
                
                if(cur > 0 && s.charAt(cur - 1) == ']' && !strs.isEmpty()) {
                    strs.push(strs.pop() + str);
                } else {
                    strs.push(str);
                }
                
                cur = right;
            }
        }
        
        StringBuilder builder = new StringBuilder();
        while(!strs.isEmpty()) {
            builder.insert(0 , strs.pop());
        }
        
        return builder.toString();
    }
    

    }


Log in to reply
 

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