394. Decode String
Posted 咖啡中不塌缩的方糖
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
Python 解LeetCode:394 Decode String