首页 > 代码库 > decode-string

decode-string

https://leetcode.com/problems/decode-string/public class Solution {    private String s;    private int newPos;        public String decodeString(String ins) {        s = ‘.‘ + ins + ‘]‘;        newPos = 0;        String outStr = impl(1, 0);        return outStr.substring(1, outStr.length());    }        private String impl(int prefix, int startPos) {        int base = 0;        String baseStr = "";        String outStr = "";                for (int i=startPos; i<s.length(); i++) {            char ch = s.charAt(i);                        if (ch == ‘[‘) {                int tmpPos = i+1;                baseStr += impl(base, tmpPos);                i = newPos;                base = 0;            }            else if (ch == ‘]‘) {                for (int j=0; j<prefix; j++) {                    outStr += baseStr;                }                // At begin, use i+1, is wrong,                // because in each loop there‘s i++                newPos = i;                return outStr;            }            else if (!Character.isDigit(ch)){                baseStr += ch;            }            else {                base = base * 10 + ch - ‘0‘;            }        }                return outStr;    }}

 

decode-string