Java stack solution using single StringBuilder


  • 0
    M
    public class Solution {
        public String decodeString(String s) {
            InnerScanner scr = new InnerScanner(s);
            StringBuilder sb = new StringBuilder();
            Deque<int[]> stack = new ArrayDeque<>();
            while (scr.hasNext()) {
                if (scr.hasNextNum()) {
                    int[] p = {scr.nextNum(), sb.length()};
                    stack.push(p);
                    scr.nextChar();
                } else {
                    char ch = scr.nextChar();
                    if (ch == ']') {
                        int[] p = stack.pop();
                        int end = sb.length();
                        for (int i = 1; i < p[0]; ++i) {
                            sb.append(sb, p[1], end);
                        }
                    } else {
                        sb.append(ch);
                    }
                }
            }
            return sb.toString();
        }
        
        private static class InnerScanner {
            private final String str;
            private final int len;
            private int ptr;
            
            public InnerScanner(String s) {
                str = s;
                len = str.length();
                ptr = 0;
            }
            
            public boolean hasNextNum() {
                return ptr < len && Character.isDigit(str.charAt(ptr));
            }
            
            public int nextNum() {
                int num = 0;
                while (Character.isDigit(str.charAt(ptr))) {
                    num = num * 10 + (str.charAt(ptr++) - '0');
                }
                return num;
            }
            
            public char nextChar() {
                return str.charAt(ptr++);
            }
            
            public boolean hasNext() {
                return ptr < len;
            }
        }
    }
    

Log in to reply
 

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