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; } }
..