LeetCode 394. Decode String 原创Java参考解答
问题描述
https://leetcode.com/problems/decode-string/
Given an encoded string, return it’s decoded string.
The encoding rule is: k[encoded_string]
, where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a
or 2[4]
.
Examples:
s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
解题思路
题目原型就是解压原理,通过被压缩的字符串的数字、字母还原出完整的字符串。
一个简单的方法是引入两个stack,一个记录倍数、一个记录字符串。
- 遍历字符串,如果遇到数字,倍数变量count++;
- 如果遇到左中括号 [ ,我们把当前count压入数字栈中,把当前result字符串压入字符串栈中,并把result重设为空字符串;
- 如果遇到右中括号 ] 时,我们pop出数字栈中顶元素,存入变量repeat,然后重复repeat次数,给字符串栈的顶元素循环加上repeat个result字符串。循环结束后,把更新过的顶元素存入字符串result中;
- 其他情况,如果遇到字母,我们直接把该位置字符加入字符串result中即可。
参考代码
public class Solution { public String decodeString(String s) { String result = ""; Stack<String> stringStack = new Stack<>(); Stack<Integer> countStack = new Stack<>(); int index = 0; while (index < s.length()) { if (s.charAt(index) >= '0' && s.charAt(index) <= '9') { int count = 0; while (s.charAt(index) >= '0' && s.charAt(index) <= '9') { count = count * 10 + (s.charAt(index) - '0'); index++; } countStack.push(count); } else if (s.charAt(index) == '[') { stringStack.push(result); result = ""; index++; } else if (s.charAt(index) == ']') { StringBuilder sb = new StringBuilder(stringStack.pop()); int repeat = countStack.pop(); for (int i = 0; i < repeat; i++) { sb.append(result); } result = sb.toString(); index++; } else { result += s.charAt(index); index++; } } return result; } }