Java recursion solution


  • 0
    D
    public class Solution {
        private String s;
        private int curIndex;
    
        public String decodeString(String s) {
            if (s == null || s.length() == 0) {
                return s;
            }
            this.s = s;
            return decodeBeginWithEither();
        }
    
        private String decodeBeginWithEither() {
            StringBuffer ret = new StringBuffer();
            if (curIndex >= s.length()) {
                return ret.toString();
            }
            while (curIndex < s.length() && s.charAt(curIndex) != ']') {
                if (Character.isDigit(s.charAt(curIndex))) {
                    ret.append(decodeBeginWithDigit());
                } else {
                    ret.append(s.charAt(curIndex));
                    curIndex++;
                }
            }
            return ret.toString();
        }
    
        private String decodeBeginWithDigit() {
            int leftBracketIndex = s.indexOf('[', curIndex);
            int repeatNum = Integer.parseInt(s.substring(curIndex, leftBracketIndex));
            curIndex = leftBracketIndex + 1;
            String repeatStr = decodeBeginWithEither();
            assert s.charAt(curIndex) == ']';
            curIndex++;
            StringBuffer ret = new StringBuffer();
            for (int i = 0; i < repeatNum; i++) {
                ret.append(repeatStr);
            }
            return ret.toString();
        }
    }
    

Log in to reply
 

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