码迷,mamicode.com
首页 > 其他好文 > 详细

decode-string

时间:2016-09-17 16:22:19      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/charlesblc/p/5878926.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!