Leetcode-decode String

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.