首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。