LeetCode解题报告 394. Decode String [medium]

来源:互联网 发布:多个虚拟机网络设置 编辑:程序博客网 时间:2024/06/05 01:56

题目描述

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".

解题思路

题目的show tags 指出是dfs和stack相关,因此考虑用栈来实现。

可以看到字符串中字符出现的顺序一定是:数字--> [ --> 字母 --> ] ,以这四个为一组。建立两个栈,一个栈a用来存储这一组中的这一个数字,表明重复的次数。另一个栈b用来存储之前已经解码好的字符串(仍然以这样的四个为一组解码好的)。用 [ 和 ] 标识进栈和出栈。每次在遇到 [ 之后,就让数字(count来标识)进栈a,进栈以后立即让count归0,为了记录下一个数字。再让已经解码好的result字符串进栈,进栈以后result重置为空,为了存储接下来会遇到的字母(四个为一组到了第三个)。最后在遇到 ] 之后,对result重复栈a的数字的n-1次(已经有一次), 将之前栈b的字符串和result加起来为新的reslut就是这四个为一组解码好的加上之前已经解码好的字符串。将栈a,栈b出栈,也就是变为空栈。

最后不断这样重复,返回result。


复杂度分析

时间复杂度为O(n*n)

代码如下:
class Solution {public:    string decodeString(string s) {        stack<int>numbers;        stack<string>chars;        int count=0;        string result="";                for (int i=0; i<s.size(); i++) {            if (isdigit(s[i])) {                count=count*10+s[i]-'0';            }            else if (s[i]=='[') {                chars.push(result);                numbers.push(count);                result="";                count=0;                            }                        else if (isalpha(s[i])) {                result.push_back(s[i]);            }                        else if (s[i]==']'){                string temp=result;                for (int j=0; j<numbers.top()-1; j++) {                    result=result+temp;                }                result=chars.top()+result;                chars.pop();                numbers.pop();                            }        }                return result;    }};



0 0