394. Decode String
来源:互联网 发布:分形设计软件 编辑:程序博客网 时间:2024/06/06 10:17
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来做。创建两个stack,一个存储integer,另一个存储单个字符串元素。同时需要注意括号前的数字有可能不是个位数,由于字符串的valid特性,数字也不会出现在字符串的末尾,因此可以判断出连续出现的数字,并用Integer.parseInt(s.substring(start, i + 1))进行转换。
class Solution { public String decodeString(String s) { Stack<Integer> num = new Stack<>(); Stack<String> res = new Stack<>(); res.push(""); for (int i = 0; i < s.length(); i++){ if (s.charAt(i) >= '0' && s.charAt(i) <= '9'){ int start = i; while (s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9'){ i++; } num.push(Integer.parseInt(s.substring(start, i + 1))); } else if (s.charAt(i) == '['){ res.push(""); } else if (s.charAt(i) == ']'){ String tmp = res.pop(); String tmpStr = ""; int n = num.pop(); for (int j = 0; j < n; j++){ tmpStr = tmpStr + tmp; } res.push(res.pop() + tmpStr); } else{ res.push(res.pop() + s.charAt(i)); } } return res.pop(); }}
- 【Leetcode】394. Decode String
- 394. Decode String
- 394. Decode String
- 394. Decode String
- 【leetcode】394. Decode String
- 394. Decode String
- leetcode ----394. Decode String
- 394. Decode String
- 394. Decode String
- 394. Decode String
- 394. Decode String
- [leetcode] 394. Decode String
- [Leetcode]394. Decode String
- 394. Decode String
- 【LeetCode】 394. Decode String
- 394. Decode String
- LeetCode 394. Decode String
- Leetcode 394. Decode String
- LeetCode145. Binary Tree Postorder Traversal(hard)
- 找出字符串中的最长连续数字子串
- 更新Windows 10 之后Kali引导丢失问题修复
- java程序路径通配符表达式合辑
- 10分钟看懂HTTPS
- 394. Decode String
- keras实验1Keras框架搭建
- Window下Tensorflow环境配置及Keras环境配置(包括各种报错解决方法)
- UML类图的6种关系
- ZAB的架构
- 611. Valid Triangle Number
- lnmp 配置laravel
- Postgresql and Postgis install under Ubuntu14.04 (trusty)
- C#--根据登录账号和密码实现登录