394. 字串解碼
阿新 • • 發佈:2020-07-15
方法一:分治,遞迴
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 { publicString 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(); } }