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< /c2> 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".
Solution:
Public classSolution { Publicstring decodestring (string s) {StringBuilder builder=NewStringBuilder (); Decodestringrecur (S.tochararray (), builder,0); returnbuilder.tostring (); } Public intDecodestringrecur (Char[] sArr, StringBuilder Builder,intstart) { if(start>=sarr.length) { returnstart; } intP1 =start; while(P1<sarr.length && sarr[p1]!= ') '){ if(sarr[p1]< ' 0 ' | | sarr[p1]> ' 9 ') {builder.append (Sarr[p1++]); } Else { //get the following encoded string. //get the number first. intval = 0; while(P1<sarr.length && sarr[p1]!= ' [') {Val= Val*10 + (int) (sarr[p1++]-' 0 '); } //get the string.StringBuilder Subbuilder =NewStringBuilder (); P1= Decodestringrecur (sarr,subbuilder,p1+1); //add into decoded string. for(inti=0;i<val;i++) {builder.append (Subbuilder); } } } return(p1<sarr.length)? P1+1: p1; }}
Leetcode-decode String