题目链接:
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".
这道题目要是用两个栈结构来进行计算,想了很长时间最后还是看的别人的答案
两个栈结构中,使用的时候要注意,存储数字的栈使用来来确定添加的次数的.每一次压栈都要注意压栈得时候应将上一个的栈中的数据清除.
public class Solution {
public String decodeString(String s) {
Stack<Integer> inStack = new Stack<>();
Stack<StringBuffer> charStack = new Stack<>();
StringBuffer sb = new StringBuffer();
int count = 0;
for(char c : s.toCharArray()) {
if(Character.isDigit(c)) count = count * 10 + c - '0';
else if(c == '[') {
inStack.add(count);
charStack.add(sb);
count = 0;
sb = new StringBuffer();
}
else if(c == ']') {
StringBuffer tem = sb;
sb = charStack.pop();
for(int k = inStack.pop(); k > 0; k--) sb.append(tem);
}
else sb.append(c);
}
return sb.toString();
}
}