Topic
- Total accepted:10087
- Total submissions:25510
- Difficulty:medium
- Contributors:admin
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< /c3> times. Note that K was guaranteed to be a positive integer.
Assume that the input string was always valid; No extra white spaces, square brackets is well-formed, etc.
Furthermore, assume that the original data does not contain any digits and that digits is only for those repeat N Umbers, K. For example, there won ' t is 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".
Solving
1 classSolution {2 Public:3 stringDecodestring (strings) {4stack<string>STRs;5stack<int>counts;6 stringresult ="";7 intCNT =0;8 for(inti =0; I < s.size (); i++) {9 if(S[i] <='9'&& S[i] >='0') {TenCNT = cnt*Ten+ S[i]-'0'; Onecout <<"Number ="<< CNT <<Endl; A}Else if(S[i] = ='[') { -cout <<"["<<Endl; - Counts.push (CNT); the Strs.push (result); - result.clear (); -CNT =0; -}Else if(S[i] = =']') { + intcur_cnt =counts.top (); -cout <<"]"<<"cur_cnt ="<< cur_cnt <<Endl; + Counts.pop (); A for(intj =0; J < cur_cnt; J + +) { atStrs.top () + =result; - } -result =strs.top (); - Strs.pop (); -}Else { -Result + =S[i]; incout <<"result + ="<< S[i] <<Endl; - } to } + returnStrs.empty ()?result:strs.top (); - } the};
Attention:
' [' Remember to clear result, initialize CNT to 0.
394. Decode String