Leetcode刷题(第394题)——字符串解码

x33g5p2x  于2022-03-31 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(178)

一、题目

二、示例

输入: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 strArr = []
    let numArr = []
    let res = ''
    let num = 0
    for(let item of s) {
        if(!isNaN(item)) {
            num = num * 10 + (item - '0')
        }else if(item === '[') {
            strArr.push(res)
            numArr.push(num)
            res = ''
            num = 0
        }else if(item === ']') {
            res = strArr.pop() + res.repeat(numArr.pop())
        }else {
            res += item
        }
    }
    return res
}

五、总结

相关文章

微信公众号

最新文章

更多