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

这道题让我们把一个按一定规则编码后的字符串解码成其原来的模样,编码的方法很简单,就是把重复的字符串放在一个括号里,把重复的次数放在括号的前面,注意括号里面有可能会嵌套括号,这题可以用递归和迭代两种方法来解,我们首先来看递归的解法,把一个括号中的所有内容看做一个整体,一次递归函数返回一对括号中解码后的字符串。给定的编码字符串实际上只有四种字符,数字,字母,左括号,和右括号。那么我们开始用一个变量i从0开始遍历到字符串的末尾,由于左括号都是跟在数字后面,所以首先遇到的字符只能是数字或者字母,如果是字母,直接存入结果中,如果是数字,循环读入所有的数字,并正确转换,那么下一位非数字的字符一定是左括号,指针右移跳过左括号,对之后的内容调用递归函数求解,注意我们循环的停止条件是遍历到末尾和遇到右括号,由于递归调用的函数返回了子括号里解码后的字符串,而我们之前把次数也已经求出来了,那么循环添加到结果中即可,参见代码如下:

解法一:

class Solution {
public:
string decodeString(string s) {
int i = ;
return decode(s, i);
}
string decode(string s, int& i) {
string res = "";
int n = s.size();
while (i < n && s[i] != ']') {
if (s[i] < '' || s[i] > '') {
res += s[i++];
} else {
int cnt = ;
while (s[i] >= '' && s[i] <= '') {
cnt = cnt * + s[i++] - '';
}
++i;
string t = decode(s, i);
++i;
while (cnt-- > ) {
res += t;
}
}
}
return res;
}
};

我们也可以用迭代的方法写出来,当然需要用 stack 来辅助运算,我们用两个 stack,一个用来保存个数,一个用来保存字符串,我们遍历输入字符串,如果遇到数字,我们更新计数变量 cnt;如果遇到左括号,我们把当前 cnt 压入数字栈中,把当前t压入字符串栈中;如果遇到右括号时,我们取出数字栈中顶元素,存入变量k,然后给字符串栈的顶元素循环加上k个t字符串,然后取出顶元素存入字符串t中;如果遇到字母,我们直接加入字符串t中即可,参见代码如下:

解法二:

class Solution {
public:
string decodeString(string s) {
string t = "";
stack<int> s_num;
stack<string> s_str;
int cnt = ;
for (int i = ; i < s.size(); ++i) {
if (s[i] >= '' && s[i] <= '') {
cnt = * cnt + s[i] - '';
} else if (s[i] == '[') {
s_num.push(cnt);
s_str.push(t);
cnt = ; t.clear();
} else if (s[i] == ']') {
int k = s_num.top(); s_num.pop();
for (int j = ; j < k; ++j) s_str.top() += t;
t = s_str.top(); s_str.pop();
} else {
t += s[i];
}
}
return s_str.empty() ? t : s_str.top();
}
};

类似题目:

Encode String with Shortest Length

Number of Atoms

参考资料:

https://leetcode.com/problems/decode-string/

https://leetcode.com/problems/decode-string/discuss/87728/share-my-c-solution

https://leetcode.com/problems/decode-string/discuss/87543/0ms-simple-C%2B%2B-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Decode String 解码字符串的更多相关文章

  1. [LeetCode] 394. Decode String 解码字符串

    Given an encoded string, return it's decoded string. The encoding rule is: k[encoded_string], where ...

  2. 394. Decode String 解码icc字符串3[i2[c]]

    [抄题]: Given an encoded string, return it's decoded string. The encoding rule is: k[encoded_string], ...

  3. [LeetCode] Decode Ways 解码方法

    A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' - ...

  4. [LeetCode] Reorganize String 重构字符串

    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to ...

  5. [LeetCode] decode ways 解码方式

    A message containing letters fromA-Zis being encoded to numbers using the following mapping: 'A' -&g ...

  6. [LeetCode] Scramble String 爬行字符串

    Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrin ...

  7. [LeetCode] Magical String 神奇字符串

    A magical string S consists of only '1' and '2' and obeys the following rules: The string S is magic ...

  8. [LeetCode] Rotate String 旋转字符串

    We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost ...

  9. [LeetCode] Decode Ways 解码方法个数、动态规划

    A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' - ...

随机推荐

  1. 读书笔记--SQL必知必会21--使用游标

    21.1 游标 结果集(result set),SQL查询说检出的结果. 游标(cusror),是一个存储在DBMS服务器上的数据库查询. 游标不是一条SELECT语句,而是被该句检索出来的结果集. ...

  2. Federated Identity Pattern 联合身份模式

    Delegate authentication to an external identity provider. This pattern can simplify development, min ...

  3. Windows Phone Toolkit 的 DatePicker 控件本地化的问题

    用到 The Windows Phone Toolkit 里的 DatePicker 控件,但是多语言的时候出现了问题: 手机设置为中文,虽然月份跟星期有效,但是 Title 却还是默认的语言:CHO ...

  4. DataAccess通用数据库访问类,简单易用,功能强悍

    以下是我编写的DataAccess通用数据库访问类,简单易用,支持:内联式创建多个参数.支持多事务提交.支持参数复用.支持更换数据库类型,希望能帮到大家,若需支持查出来后转换成实体,可以自行扩展dat ...

  5. 翻译:使用 ASP.NET MVC 4, EF, Knockoutjs and Bootstrap 设计和开发站点 - 2

    我们的目标: 需求 Screen 1: 联系人列表 - 查看所有联系人 1.1 这个 screen 将显示数据库中的所有联系人. 1.2 用户可以删除任何联系人.1.3 用户可以编辑任何联系人的详细信 ...

  6. Yii 2.x Behavior - 类图

    yii\base\Component  继承这个类的类都具备扩展行为的能力

  7. C标准头文件<errno.h>

    声明了错误处理相关的宏 errno errno即error number,在程序启动时被设为0,当某个库函数运行出现错误的时候,会将相应的能表达错误类型的数字赋值给这个左值,这些数字往往有相应的宏来表 ...

  8. js与java正则表达式处理字符串问题

    在编写处理字符串的程序或网页时,经常会有查找符合某些复杂规则的字符串的需要.正则表达式就是用于描述这些规则的工具.换句话说,正则表达式就是记录文本规则的代码.合理使用正则表达式确实会为程序员省去很多字 ...

  9. jdk源码分析ArrayDeque

    ArrayDeque 数组循环队列,这个数据结构设计的挺有意思的. 据说此类很可能在用作堆栈时快于 Stack,在用作队列时快于 LinkedList. 一.容量 1.1默认容量是8=2^3 1.2指 ...

  10. Atitit 软件国际化原理与概论

    Atitit 软件国际化原理与概论 语言和文化习俗因地域不同而差别很大.对某一特定的地域的 语言环境称为"locale".它不仅包括语言和货币单位,而且还包括 数字标示格式, 日期 ...