394. Decode String

网友投稿 597 2022-10-09

394. Decode String

394. 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".

class Solution public String decodeString(String s) { String res = ""; Stack countStack = new Stack<>(); Stack resStack = new Stack<>(); int idx = 0; while (idx < s.length()) { if (Character.isDigit(s.charAt(idx))) { int count = 0; while (Character.isDigit(s.charAt(idx))) { count = 10 * count + (s.charAt(idx) - '0'); idx++; } countStack.push(count); } else if (s.charAt(idx) == '[') { resStack.push(res); res = ""; idx++; } else if (s.charAt(idx) == ']') { StringBuilder temp = new StringBuilder(resStack.pop()); int repeatTimes = countStack.pop(); for (int i = 0; i < repeatTimes; i++) { temp.append(res); } res = temp.toString(); idx++; } else { res += s.charAt(idx++); } } return

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:云开发·头像合成小程序,可以用于在小程序端生成包含不同边框的头像
下一篇:微信小程序-移动端小商城
相关文章

 发表评论

暂时没有评论,来抢沙发吧~