zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    MyBatis入门(一)—— 入门案例
    Spring Boot统一异常处理方案示例
    Centos7 安装 ActiveMq
    在 CentOS7 上安装 zookeeper-3.5.2 服务
    使用Homebrew安装Git与Github在idea中的配置
    iReport(模版) 与Jasper(数据填充)生成pdf文档
    SSH下shiro的基本使用
    FastJson的忽略字段和格式日期用法
    Quartz —— 任务调度框架
    POI操作Excel
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5874653.html
Copyright © 2011-2022 走看看