leetcode394.字符串编码

leetcode394.字符串编码

题目

给定一个经过编码的字符串,返回它解码后的字符串。

编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。

你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

用例

输入:s = "3[a]2[bc]"
输出:"aaabcbc"
输入:s = "3[a2[c]]"
输出:"accaccacc"
输入:s = "2[abc]3[cd]ef"
输出:"abcabccdcdcdef"
输入:s = "abc3[cd]xyz"
输出:"abccdcdcdxyz"

求解

/**
 * @param {string} s
 * @return {string}
 */
var decodeString = function(s) {
    let stack1 =[]
    let stack2= []
    for(let i=0;i<s.length;i++){
        if(s[i]!=']'){
            stack1.push(s[i])
        }else{
            let top_stack1=stack1[stack1.length-1]
            //将[]中的内容转移到stack2中
            while(top_stack1!='['){
                stack1.pop()
                stack2.push(top_stack1)
                top_stack1=stack1[stack1.length-1]
            }
            stack1.pop()
            //根据[]前面的数字复制n遍到stack1中
            let n=''
            //获取前面的数字
            top_stack1=stack1[stack1.length-1]
            while(stack1.length>0&&top_stack1.charCodeAt()>=48&&top_stack1.charCodeAt()<=57){
                n=top_stack1+n
                stack1.pop()
                top_stack1=stack1[stack1.length-1]
            }
            n=parseInt(n)
            for(let i=0;i<n;i++){
                for(let j=0;j<stack2.length;j++){
                    stack1.push(stack2[stack2.length-j-1])
                }
            }
            while(stack2.length>0){
                stack2.pop()
            }
        }
    }
    let res =''
    for(v of stack1.values()){
        res=res+v
    }
    return res
};
posted @ 2021-12-23 15:56  BONiii  阅读(27)  评论(0)    收藏  举报