1. 程式人生 > 遊戲 >貪玩藍月發行方被爆大規模裁員

貪玩藍月發行方被爆大規模裁員

394. 字串解碼

package 字串;

import java.util.Stack;

public class 字串解碼 {
    public static void main(String[] args) {
        String s = "3[a2[c]]";
        字串解碼 o = new 字串解碼();
        String s1 = o.decodeString(s);
        System.out.println(s1);
    }


    // 利用棧找中括號的另一半,遇到中括號左邊就去找另一半
    // 將中括號裡面的字元複寫
    
// 反覆遞迴,直到字串中不含有左半邊中括號為止 public String decodeString(String s) { if (!s.contains("[")) { return s; } char[] chars = s.toCharArray(); int i = 0; while (chars[i] != '[' && i < chars.length) { i++; } int end = getNextIndex(chars, i); String s1
= deCodeIndex(s, i, end); return decodeString(s1); } public int getNextIndex(char[] chars, int i) { Stack<Character> stack = new Stack<>(); stack.push(chars[i]); int j = i + 1; while (!stack.isEmpty()) { if (chars[j] == '[') { stack.push(
'['); } if (chars[j] == ']') { stack.pop(); } j++; } return --j; } public String deCodeIndex(String s, int start, int end) { String s1 = ""; String s3 = s.substring(end + 1, s.length()); String s2 = ""; String k=""; int numStart=-1; for (int i = 0; i < start; i++) { if(s.charAt(i)>='0' && s.charAt(i)<='9'){ k+=String.valueOf(s.charAt(i)); if(numStart==-1){ numStart=i; } } } if(numStart>0){ s1 = s.substring(0, numStart); } int count=Integer.parseInt(k); for (int i = 0; i < count; i++) { s2 += s.substring(start + 1, end); } return s1 + s2 + s3; } }

..