394. Decode String

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 thatk 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 or2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".s = "3[a2[c]]", return "accaccacc".s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

这道题可以充分利用递归的优势哦,一步一步读就好了:

var decodeString = function(str) {
    var len = str.length;
    var time = 0;
    var qcount = 0;
    var needToTime = "";
    var temp = "";
    for (var i = 0;i < len;i++) {
        if (qcount===0) {
            if (str[i]<='9'&&str[i]>='0') {
                time*=10;
                time+=parseInt(str[i]);
            }
            else if (str[i]==='['){
                qcount=1;
            } else {
                temp+=str[i];
            }
        } else {
            if (str[i]==='['){
                qcount+=1;
                needToTime+=str[i];
            } else if (str[i]===']'){
                qcount-=1;
                if (qcount!==0) {
                    needToTime+=str[i];
                } else {
                    var decoded = decodeString(needToTime);
                    for (var j = 0;j < time;j++)
                        temp+=decoded;
                    needToTime="";
                    time = 0;
                }
            } else {
                needToTime+=str[i];
            }
        }
    }
    return temp;
};

你可能感兴趣的:(394. Decode String)