码迷,mamicode.com
首页 > 其他好文 > 详细

394. Decode String

时间:2016-09-15 13:43:53      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/renyualbert/p/5874653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!