Short one stack Java solution without regex


  • 0
    public class Solution {
        public String decodeString(String s) {
            if (s == null) return null;
            Deque<String> stack = new ArrayDeque();
            int num = 0;
            for (int i = 0; i < s.length(); ++i) {
                char c = s.charAt(i);
                if (Character.isDigit(c)) num = 10 * num + (c - '0');
                else if (c == '[') {
                    stack.offer(String.valueOf(num));
                    stack.offer("[");
                    num = 0;
                }
                else if (c == ']') {
                    String pattern = "";
                    while (!(stack.peekLast()).equals("[")) pattern = stack.pollLast() + pattern;
                    stack.pollLast();
                    int k = Integer.parseInt(stack.pollLast());
                    StringBuilder str = new StringBuilder();
                    while (k-- > 0) str.append(pattern);
                    stack.offer(str.toString());
                }
                else stack.offer(c + "");
            }
            StringBuilder sb = new StringBuilder();
            while (!stack.isEmpty()) sb.append(stack.pollFirst());
            return sb.toString();
        }
    }
    

Log in to reply
 

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