前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0394 - Decode String

LeetCode 0394 - Decode String

作者头像
Reck Zhang
发布2021-08-11 11:05:47
3330
发布2021-08-11 11:05:47
举报
文章被收录于专栏:Reck Zhang

Decode String

Desicription

Given an encoded string, return its 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:

代码语言:javascript
复制
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

Solution

代码语言:javascript
复制
class Solution {
public:
    std::string decodeString(const std::string& s) {
        std::stack<std::pair<int, std::string>> stack = {};
        stack.push({0, ""});
        int count = 0;
        for(const auto& c: s) {
            if(c >= '0' && c <= '9') {
                count = count * 10 + c - '0';
            } else if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
                stack.top().second += c;
            } else if(c == '[') {
                stack.push({count, ""});
                count = 0;
            } else if(c == ']') {
                auto top = stack.top();
                stack.pop();
                while(top.first--) {
                    stack.top().second += top.second;
                }
            }
        }
        return stack.top().second;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-09-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Decode String
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档