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 Tuning 基础概述03 - 使用sql_trace和10046事件跟踪执行计划

    1.使用sql_trace跟踪执行计划 1.1 当前session跟踪: alter session set sql_trace = true; //开始sql_trace alter session ...

  2. 跟我学习NHibernate (1)

    引言:Nibernate概述 NHibernate是一个ORM框架,NHibernate是一个把C#对象世界和关系世界数据库之间联系起来的一座桥梁.NHibernate 能自动映射实体模型到数据库,所 ...

  3. ASP.NET Core 中文文档 第二章 指南(4.3)添加 View

    原文:Adding a view 作者:Rick Anderson 翻译:魏美娟(初见) 校对:赵亮(悲梦).高嵩(Jack).娄宇(Lyrics).许登洋(Seay).姚阿勇(Dr.Yao) 本节将 ...

  4. [C1] C1FlexGrid 排除非绑定列的验证效果

    一.前言 前提是 C1FlexGrid 中存在数据绑定列和自定义列(非数据绑定列),此时如果该行编辑后出现排他错误,自定义列也会出现验证结果的红色边框: 但是自定义列如果只是一些按钮操作,提示说明什么 ...

  5. C#开发微信门户及应用(7)-微信多客服功能及开发集成

    最近一直在弄微信的集成功能开发,发现微信给认证账户开通了一个多客服的功能,对于客户的咨询,可以切换至客服处理的方式,而且可以添加多个客服进行处理,这个在客户咨询比较多的时候,是一个不错的营销功能.微信 ...

  6. Linux下安装Redis

    1. 下载最新版本的Redis源代码: 命令:wget http://download.redis.io/redis-stable.tar.gz 2. 解压并编译 命令:tar xzf redis-s ...

  7. 包含修改字体,图片上传等功能的文本输入框-Bootstrap

    通过jQuery Bootstrap小插件,框任何一个div转换变成一个富文本编辑框,主要特色: 在Mac和window平台下自动针对常用操作绑定热键 可以拖拽插入图片,支持图片上传(也可以获取移动设 ...

  8. GJM : Unity3D HIAR -【 快速入门 】 三、导入 SDK

    导入 SDK 本文将向您介绍如何在 Unity 工程中导入 HiAR SDK for Unity.在开始之前,请先访问 HiAR 官网下载最新版本的 SDK. 下载 HiAR SDK for Unit ...

  9. hello,world!

    我是马燕,在2017即将来临之际,我希望自己,在新的一年里,能开开心心,健健康康,家人平平安安! 我会努力工作,努力学习,离自己的理想越来越接近. 以后我会将我的所学所得写在这里,供未来的自己随时查看 ...

  10. SVG颜色、渐变和填充

    颜色 RGB和HSL都是CSS3支持的颜色表示方法,一般普遍使用是RGB.PS:HSL浏览器兼容. RGB RGB即是代表红.绿.蓝三个通道的颜色,通过对红(R).绿(G).蓝(B)三个颜色通道的变化 ...