给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = “3[a]2[bc]”, 返回 “aaabcbc”. s = “3[a2[c]]”, 返回 “accaccacc”. s = “2[abc]3[cd]ef”, 返回 “abcabccdcdcdef”.
学到了: String rer = “”; rer = stack.pop()+rer;
判断字符到数字范围 s.charAt(0)>‘0’&&s.charAt(0)<‘9’ 解题思路:就是遇到数字字符都压入栈中。碰到"]"符号,就弹栈直到找到“[” 并将之前的数字也找到。技巧就是上面2个小技巧。
class Solution { public static String decodeString(String s) { StringBuilder sbs = new StringBuilder(); Stack<String> stack = new Stack<>(); for(int i = 0;i<s.length();i++) { char c = s.charAt(i); if(c!=']') { String sq = ""; stack.push(sq+c); }else{ //学到的东西 String o = ""; while(!stack.peek().equals("[")){ o = stack.pop()+o; } stack.pop(); String count = ""; while(!stack.isEmpty()&&stack.peek().charAt(0)>='0'&&stack.peek().charAt(0)<='9') { count = stack.pop()+count; } int countNum = Integer.parseInt(count); String ret = ""; for(int j = 0;j<countNum;j++) { ret = ret+o; } stack.push(ret); } } String op = ""; while(!stack.isEmpty()) { op= stack.pop()+op; } return op; } }