首页 > 代码库 > 394. Decode String

394. Decode String

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 kis 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 or2[4].

Examples:

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


这道题是典型的DFS的题,用stack存进去一直到“]”,然后取到下一个有letter的地方。pop up 的新的string要放进stack里。
public string DecodeString(string s) {        if(s.Length == 0) return s;        var stack = new Stack<string>();        string ss = "";        string res = "";        var digitList = new List<string>(){"0","1","2","3","4","5","6","7","8","9"};        for(int i =0;i< s.Length;i++)        {                        if(s[i] == [)            {                stack.Push(s[i]+"");                ss = "";            }            else if(s[i] == ])            {                while(stack.Peek() != "[" )                {                    ss = stack.Pop()+ss;                }                stack.Pop();                string num = "";//in case "30a"                while(stack.Count()>0 && digitList.Contains(stack.Peek()) )                {                    num = stack.Pop() + num;                }                                int multi = Int32.Parse(num);                string oldss = ss;                for(int j = 1;j<multi;j++)                {                    ss = ss+oldss;                }                stack.Push(ss);                ss = "";                          }            else if(Char.IsLetter(s[i]))            {                ss += s[i];            }            else            {                             if(ss != "") stack.Push(ss);                ss = "";                stack.Push(s[i]+"");            }        }        if(ss != "") res =ss; //in case ef in "dd30[a]2[bc]ef"        while(stack.Count()>0)        {            res = stack.Pop()+res;        }        return res;    }

 

394. Decode String