Decode String
来源:互联网 发布:安装双系统win7和linux 编辑:程序博客网 时间:2024/05/23 23:48
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".
java
class Solution { public String decodeString(String s) { if (s == null || s.length() == 0) { return ""; } Stack<Object> stack = new Stack<>(); int num = 0; for (char c : s.toCharArray()) { if (Character.isDigit(c)) { num = num * 10 + c - '0'; } else if (c == '[') { stack.push(Integer.valueOf(num)); num = 0; } else if (c == ']') { String str = util(stack); int count = (int)stack.pop(); for (int i = 0; i < count; i++) { stack.push(str); } } else { stack.push(String.valueOf(c)); } } return util(stack); } private String util(Stack<Object> stack) { StringBuffer sb = new StringBuffer(); Stack<String> stack1 = new Stack<>(); while (!stack.empty() && stack.peek() instanceof String) { stack1.push((String)stack.pop()); } while (!stack1.empty()) { sb.append(stack1.pop()); } return sb.toString(); }}python
class Solution: """ @param: s: an expression includes numbers, letters and brackets @return: a string """ def expressionExpand(self, s): # write your code here if s is None or len(s) == 0: return "" num = 0 stack = [] for element in s: if element.isdigit(): num = num * 10 + int(element); elif element is '[': stack.append(num) num = 0 elif element is ']': s = self.util(stack) count = stack.pop() for i in range(count): stack.append(s) else: stack.append(element) return self.util(stack) def util(self, stack): s = [] while len(stack) != 0 and isinstance(stack[-1], str): s.append(stack.pop()) s.reverse() return "".join(s)
阅读全文
0 0
- Decode String
- Decode String
- Decode String
- Decode String
- Decode String
- Decode String
- Decode String
- Decode String
- Decode String
- Decode String
- Decode String
- 【Leetcode】394. Decode String
- 394. Decode String
- 394. Decode String
- 394. Decode String
- [Leetcode] Decode String
- [394]Decode String
- 【leetcode】394. Decode String
- Java9学习(1):Java9安装与开发工具选择
- Docker常用命令原理图
- vs2013调用ffmpeg(不可调试)
- 程序是从main主函数开始运行吗?
- 源码分析RocketMQ之消息消费
- Decode String
- 线程同步 synchronized关键字使用
- accounting assistant
- nullptr关键字
- hdu5692 Snacks(线段树+dfs序)
- js所能表示的最大整数的问题
- spark自定义累加器
- ODBC
- HTML中的标签系列-03-DIV标签&CSS