题目:
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 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".直接算的,没用用递归。递归写来应该好看点。没仔细看题,其实发现数字就直接开始递归就行了,还在想怎么去判断
bool f(string s) { for(int i = 0; i <s.size(); i++) { if(s[i]<'A'||s[i]>'z') return 0; } return 1; } class Solution { public: string decodeString(string &s) { string re= ""; int len = s.size(); for(int i = 0; i < len; i++) { if(s[i] >= 'A'&&s[i] <='z') { re+=s[i]; } else { int count = 0; while(s[i]>='0'&&s[i]<='9') { count = count*10+s[i]-'0'; i++; } i++; string tem=""; int flag = 1; while(1) { if(s[i] == '[') { tem = tem +s[i]; flag++; i++; } else { if(s[i] == ']'){ flag--; if(flag == 0) { break; } else { tem = tem + s[i]; i++; } } else { tem = tem + s[i]; i++; } } } while(count--) { re = re + tem; } } } s = re; if(f(re) == 0){ return decodeString(s); } return re; } };