首页 > 编程学习 > leetcode394-字符串解码

leetcode394-字符串解码

发布时间:2022/9/2 0:52:01

字符串解码

  • 递归
class Solution {
    public String decodeString(String s) {
        StringBuilder sb = new StringBuilder();
        int i = 0, n = s.length();
        while(i < n){
            if(s.charAt(i) >= '0' && s.charAt(i) <= '9'){
                int j = i+1;
                while(s.charAt(j) >= '0' && s.charAt(j) <= '9') j++;
                int repeat = Integer.parseInt(s.substring(i, j));
                i = j;
                j++;
                int cnt = 1;
                while(cnt != 0){
                    if(s.charAt(j) == '[')  cnt++;
                    else if(s.charAt(j) == ']') cnt--;
                    j++;
                }
                String str = decodeString(s.substring(i+1, j-1));
                for(int k = 0; k < repeat; k++) sb.append(str);
                i = j;
            }else{
                sb.append(s.charAt(i));
                i++;
            }
        }
        return sb.toString();
    }
}
Copyright © 2010-2022 mfbz.cn 版权所有 |关于我们| 联系方式|豫ICP备15888888号