394. 字符串解码
方法一:分治,递归
class Solution { int index = 0; // 全局变量记录遍历到的位置 public String decodeString(String s) { int n = s.length(); StringBuilder sb = new StringBuilder(); int num = 0; for(; index < s.length(); index++) { if(Character.isDigit(s.charAt(index))) { num = num * 10 + s.charAt(index) - '0'; // 记录个数 } else if (s.charAt(index) == '[') { index++; String str = decodeString(s); // 遇到左括号,递归计算这个括号内的解码字符串 for(int i = 0; i < num; i++) { // 然后添加 sb.append(str); } num = 0; // 置0 } else if (s.charAt(index) == ']') { return sb.toString(); // 遇到右括号结束递归返回给上一层 } else { sb.append(s.charAt(index));// 是字符就添加 } } return sb.toString(); } }
方法二:利用辅助栈遇到右括号,依次弹出记录本次括号内的字符串
class Solution { public String decodeString(String s) { char[] arr = s.toCharArray(); Stack<Character> stack = new Stack<>(); for(char c : arr) { if(c != ']') { stack.push(c); } else { StringBuilder sb = new StringBuilder(); while(!stack.isEmpty() && stack.peek() != '[') { sb.append(stack.pop()); } stack.pop(); StringBuilder num = new StringBuilder(); while(!stack.isEmpty() && Character.isDigit(stack.peek())) { num.append(stack.pop()); } int n = Integer.parseInt(num.reverse().toString()); for(int j = 0; j < n; j++) { for(int i = sb.length() - 1; i >= 0; i--) { stack.push(sb.charAt(i)); } } } } StringBuilder sb = new StringBuilder(); while(!stack.isEmpty()) { sb.append(stack.pop()); } return sb.reverse().toString(); } }