Java 2 Stacks Solution - Reference Basic Calculator


  • 2
    S
    public String decodeString(String s) {
            if (s.length() == 0) return "";
            Stack<String> letter = new Stack<>();
            Stack<Integer> times = new Stack<>();
            StringBuilder sb = new StringBuilder();
            
            for (int i = 0; i < s.length(); i++) {
                if (Character.isLetter(s.charAt(i))) {
                    sb.append(s.charAt(i));
                }
                else if (Character.isDigit(s.charAt(i))) {
                    int time = s.charAt(i) - '0';
                    while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) {
                        time = time * 10 + s.charAt(i + 1) - '0';
                        i++;
                    } 
                    times.push(time);
                    letter.push(sb.toString());
                    sb = new StringBuilder();
                }
                else if (s.charAt(i) == ']') {
                    sb = constructStringBuidler(sb, letter, times);
                }
            }
            
            return sb.toString();
        }
        
        private StringBuilder constructStringBuidler(StringBuilder sb, Stack<String> letter,        Stack<Integer> times) {
            StringBuilder res = new StringBuilder();
            int time = times.pop();
            String prev = letter.pop(), curr = sb.toString();
            res.append(prev);
            
            for (int i = 0; i < time; i++) {
                res.append(sb);
            }
            
            return res;
        }
    

Log in to reply
 

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