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] 394. Decode String 解码字符串的更多相关文章

  1. [LeetCode] 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 -- 394. Decode String

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

  4. Leetcode 91. Decode Ways 解码方法(动态规划,字符串处理)

    Leetcode 91. Decode Ways 解码方法(动态规划,字符串处理) 题目描述 一条报文包含字母A-Z,使用下面的字母-数字映射进行解码 'A' -> 1 'B' -> 2 ...

  5. 394 Decode String 字符串解码

    给定一个经过编码的字符串,返回它解码后的字符串.编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次.注意 k 保证为正整数.你可以认 ...

  6. 【LeetCode】394. Decode String 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 栈 日期 题目地址:https://leetcode ...

  7. Python 解LeetCode:394 Decode String

    题目描述:按照规定,把字符串解码,具体示例见题目链接 思路:使用两个栈分别存储数字和字母 注意1: 数字是多位的话,要处理后入数字栈 注意2: 出栈时过程中产生的组合后的字符串要继续入字母栈 注意3: ...

  8. 【leetcode】394. Decode String

    题目如下: 解题思路:这种题目和四则运算,去括号的题目很类似.解法也差不多. 代码如下: class Solution(object): def decodeString(self, s): &quo ...

  9. [LeetCode] 91. Decode Ways 解码方法

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

随机推荐

  1. php explode容易犯的错误

    php explode容易犯的错误 <pre> $pos = strpos($v, 'Controller'); if (is_numeric($pos)) { $kongzhiqifeg ...

  2. IEEE 二进制浮点数的表示

    朋友在谈一个物流相关的项目,是以前项目的一个延续,涉及到后台的扩展,手机端的App,外加两个App的对接的蓝牙打印机.这个项目前后说了一个多月了吧,最近才草拟了协议.项目本来不复杂,但是客户却如此的拖 ...

  3. 简明了解apply()和call()

    apply()和call()都是ES6语法的,并且都是函数的方法. function foo() { alert(this.name) } var obj = { name: '小明' } foo() ...

  4. python asyncio call_soon, call_at, call_later

    1. call_soon, 协程一运行就马上运行 def callback(sleep_times): print("success time {}".format(sleep_t ...

  5. Spring自动注入,类型注入、名称注入(两种方式)

    参考: https://blog.csdn.net/qq_41767337/article/details/89002422 https://www.iteye.com/blog/breezylee- ...

  6. 使用 jQuery.TypeAhead 让文本框自动完成 (一)(最简单的用法)

    项目地址:https://github.com/twitter/typeahead.js 直接贴代码了: @section headSection { <script type="te ...

  7. 自己动手搭建经典的3层 Asp.Net MVC

    1:IBaseDAL using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expr ...

  8. win7搭建本地SonarQube环境进行c#代码分析

    1.SonarQube需要正常运行,首先需要安装Java环境,我这里安装的是jdk-8u181版本,可以在下面网站找适的版本去下载安装 https://www.oracle.com/technetwo ...

  9. Spring Boot @EnableAutoConfiguration解析

    刚做后端开发的时候,最早接触的是基础的spring,为了引用二方包提供bean,还需要在xml中增加对应的包<context:component-scan base-package=" ...

  10. CSS 选择器大全

    在CSS中,选择器是用于选择要设置样式的元素的模式. 选择器 例子 描述 .class .intro 选择class=“intro”的所有元素 #id #firstname 选择id=“firstna ...