本文主要是介绍LeetCode394 Decode String java solution,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:
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();}
}
这篇关于LeetCode394 Decode String java solution的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!