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;
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 7,972评论 0 0
  • 394- Decode String**QuestionEditorial Solution My Submiss...
    番茄晓蛋阅读 2,498评论 0 0
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,364评论 0 33
  • 我,网名NinaChen,很高兴认识大家,也很荣幸能跟着几位博学多才积极向上的老师学习论语,昨晚的开学典礼我听得很...
    NinaChen阅读 3,043评论 0 1
  • 今天吃完早饭,我和妈妈就开始做馒头。先把面粉倒进盆子里,然后把酵母粉放进去。我也想像妈妈那样用手去搞搞,但是...
    Cherry多多阅读 1,562评论 1 1

友情链接更多精彩内容