首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode 0394 - Decode String

LeetCode 0394 - Decode String

作者头像
Reck Zhang
发布于 2021-08-11 11:05:47
发布于 2021-08-11 11:05:47
6010
举报
文章被收录于专栏:Reck ZhangReck 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 删除
目录
  • Decode String
    • Desicription
    • Solution
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档