题目与解释

给定一个经过编码的字符串,返回它解码后的字符串。

编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。

你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a2[4] 的输入。

示例:

s = "3[a![](https://img2018.cnblogs.com/blog/1575923/201903/1575923-20190304151000879-833294601.png)

]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".

解释:

这道实际上是一道字符串与栈结合的问题。如何看出是栈结合的问题呢?

  1. 有匹配('['和']')的情况,需要使用栈来完成匹配过程
  2. 有递归的情况, 如3[2[ab]]这样

在匹配符号上,我参照我之前写的小型计算器的符号匹配,遇到']'就去寻找最近出现的匹配符号'['。

思路

建立一个字符栈,这里用的是STL自带的stack<char>

逐个读入字符压入栈,当遇到']'符号就寻找最近的匹配符号。

这个寻找的过程就是不断判断栈顶是否为'['符号?

->否。这个是括号内的字符,暂时存入一个字符串ss

->是。则寻找到匹配的字符,继续往前寻找'['的字符前的所有"数字字符串",如34[22[ss]],那么22就是[ss]的数字字符串,34则是[22[ss]]的数字字符串。在寻找完后需要将这个字符串转换成实际的数字。

经过一次上述过程后,已经知道一个括号内字符串和这段字符串出现的次数k。我们把k个字符串压入我们创建的字符栈。

而当所有字符都读完了,则转换实际上就已经结束了。我们先根据思路写一段解法,但效率还不是很高。

我们看看"3[a1[b]]"的图例

class Solution {
public:
string decodeString(string s) {
string ans = "";
stack<char>st;
/*visit all the character in the string s*/
for (unsigned i = 0; i < s.length(); i++) {
if (s[i] != ']')st.push(s[i]);
else {
/*
if we find the character ']', it means we find a pair.
string ss means the string in the pair of this times.
string num means the number k in the pair of this times.
Initialize these two strings as an empty string.
*/
string ss = "", num = "";
while (st.top() != '[') {
ss += st.top();
st.pop();
}
/*Delete '[' character*/
st.pop();
/*reverse the string ss*/
reverse(ss.begin(), ss.end());
while (!st.empty() && st.top() <= '9'&&st.top() >= '0') {
num += st.top();
st.pop();
}
unsigned times = 0, index = 1;
for (unsigned i = 0; i < num.length(); i++, index =index* 10) {
times += index * (num[i]-'0');
}
string sss ="";
for (unsigned i = 0; i < times; i++) {
sss += ss;
}
for (unsigned i = 0; i < sss.length(); i++) {
st.push(sss[i]);
}
}
}
/* push the k times string to the stack st*/
while (!st.empty()) {
ans += st.top();
st.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
};

很暴力的按照思路的过程写了代码,优化点是可以自己写一个stack而不是使用STL的stack,使这个自己写的stack拥有遍历的方法。新增的内容有注释提示。能将上面代码优化4ms。

/*********added below*********/
class Stack {
public:
Stack() {
topNum = -1;
ll.clear();
}
void push(char c) {
ll.push_back(c);
topNum++;
}
char top() {
return ll[topNum];
}
void pop() {
ll.pop_back();
topNum--;
}
bool empty() {
return topNum == -1;
}
vector<char>ll;
private:
int topNum;
};
/******add above*********/
class Solution {
public:
string decodeString(string s) {
string ans = "";
Stack* st=new Stack();
for (unsigned i = 0; i < s.length(); i++) {
if (s[i] != ']')st->push(s[i]);
else {
string ss = "", num = "";
while (st->top() != '[') {
ss += st->top();
st->pop();
}
st->pop();
/*Delete '[' character*/
reverse(ss.begin(), ss.end());
while (!st->empty() && st->top() <= '9'&&st->top() >= '0') {
num += st->top();
st->pop();
}
unsigned times = 0, index = 1;
for (unsigned i = 0; i < num.length(); i++, index =index* 10) {
times += index * (num[i]-'0');
}
string sss ="";
for (unsigned i = 0; i < times; i++) {
sss += ss;
}
for (unsigned i = 0; i < sss.length(); i++) {
st->push(sss[i]);
}
}
}
/******change below********/
for (char it : st->ll) {
ans += it;
}
/******change above********/
delete st;
return ans;
}
};

[Leetcode]394.字符串解码的更多相关文章

  1. LeetCode 394. 字符串解码(Decode String) 44

    394. 字符串解码 394. Decode String 题目描述 给定一个经过编码的字符串,返回它解码后的字符串. 编码规则为: k[encoded_string],表示其中方括号内部的 enco ...

  2. Java实现 LeetCode 394 字符串解码

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

  3. [LeetCode]394. 字符串解码(栈)

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

  4. Leetcode 394.字符串编码

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

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

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

  6. [LeetCode] Decode String 解码字符串

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

  7. 字符串解码DecodeString

    字符串解码 原创博客,转载请注明出处!eg:ss=2[abc]3[cd]ef   return:abcabccdcdcdefss=3[a2[c]]2[a]    return:accaccaccaas ...

  8. [PHP]对Json字符串解码返回NULL的一般解决方案

    ---------------------------------------------------------------------------------------------------- ...

  9. Leetcode中字符串总结

    本文是个人对LeetCode中字符串类型题目的总结,纯属个人感悟,若有不妥的地方,欢迎指出. 一.有关数字 1.数转换 题Interger to roman和Roman to integer这两题是罗 ...

随机推荐

  1. Springboot学习04-默认错误页面加载机制源码分析

    Springboot学习04-默认错误页面加载机制源码分析 前沿 希望通过本文的学习,对错误页面的加载机制有这更神的理解 正文 1-Springboot错误页面展示 2-Springboot默认错误处 ...

  2. Django中操作Redis

    一 创建redis连接池 redis_pool.py pool = redis.ConnectionPool(host='10.211.55.4', port=6379) 二 引入连接池 import ...

  3. jfinal处理完html提交过来的数据,将处理信息返回给html页面。html根据返回值进行相应的处理

    1.前台jQuery代码: $.ajax({ url: "/admin/jcsjpz/syxmdy/RemoveSyxm", data: {data: id}, success: ...

  4. (转)经验分享:CSS浮动(float,clear)通俗讲解

    文章转自:https://www.cnblogs.com/iyangyuan/archive/2013/03/27/2983813.html 很早以前就接触过CSS,但对于浮动始终非常迷惑,可能是自身 ...

  5. GUI学习之一——PyQt5初识

    我们在第〇篇里先演示了GUI的功能,其实Python有多个库是支持GUI编程的,python官网列出了大量的说明,其中包括了原生的tkinter 还有许多第三方库 Pyqt PySide wxPyth ...

  6. Spring事务传递

    2018-09-25 @Transactional(propagation=Propagation.NEVER) public void update(){ Session s = sessionFa ...

  7. 3.在自己的bag上运行Cartographer ROS

    1.验证自己的bag cartographer ROS提供了一个工具cartographer_rosbag_validate来自动分析包中的数据.在尝试调试cartographer之前运行这个工具. ...

  8. PowerDesigner 缺省值 引号 问题

    在使用PowerDesigner做为MySQL数据库建模的时候,总是有这样的问题,例如我需要一个字段 createTime 类型是 Timestamp,要求这个字段默认值为系统当前时间,于是我给这个字 ...

  9. 腾讯云的基本配置(centos 7.1)及mysql的使用

    因为想在微信上开发些东西,所以租用了一个月的腾讯云. 推荐选择的镜像是centos7.1.这个系统的选择和本地操作系统基本没有关系. 首先要登录到云主机中,用户名是root,密码是当初自己设置的那一个 ...

  10. RQNOJ 1 明明的随机数

    查重和排序,这里我用的set进行存储数据,利用了set的唯一性和自动性,方便了很多 #include <iostream> using namespace std; #include &l ...