Given an encoded string, return its 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 k is 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
or 2[4]
.
Examples:
s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
A:
#include <ctype.h> class Solution { public: string decodeString(string s) { vector<string> res; int left = 0; while(left<s.length()) { char ch = s[left]; if(isdigit(ch)) { int right = left+1; while(right<s.length() && isdigit(s[right])) right++; // now right point to '[' int count = stoi(s.substr(left, right-left)); left = right; int countOfLeftMinusRight = 0; while(right<s.length() ) { if(s[right]=='[') { countOfLeftMinusRight++; }else if(s[right]==']') { countOfLeftMinusRight--; } if(countOfLeftMinusRight == 0) { break; } right++; } string subRes = decodeString(s.substr(left+1, right -left-1)); for(int i =0;i<count;++i) res.push_back(subRes); left = right+1; }else{ res.push_back(s.substr(left,1)); ++left; } } string myresult=""; for(auto tmp:res) myresult += tmp; return myresult; } };
Mistakes:
一开始没有考虑嵌套的情况
No comments:
Post a Comment