字符串算术运算(企业原题,JavaScript)

2021秋招部分笔试题汇总
企业提供原题

[编程题]字符串算术运算
时间限制:C/C++ 1秒,其他语言2秒

空间限制:C/C++ 256M,其他语言512M

给定一个字符串式子,返回它的计算结果。算术规则为: k*[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。e.g. s = “3*[a2*[c]]”, 返回 “accaccacc”

输入例子1:
“3*[a2*[c]]”

输出例子1:
“accaccacc”

思路:
通过切割[获取需要重复的元素及内容,[前两位开始是次数,后一位开始是字母,特别注意,字母不一定只有一个,数字也可能是几位数字,需要进行额外判断

function computeString(str) {
    
    
    let res = '',
        target = '',
        index
    while (str.lastIndexOf('[') > 0) {
    
    
        index = str.lastIndexOf('[')
        let numIndex = index - 2,
            letterIndex = index + 1,
        num = ''
        item = ''
        //计算重复次数
        while (numIndex >= 0) {
    
    
            if (!/[0-9]/.test(str[numIndex])) break
            num = str[numIndex] + num
            numIndex--
        }
        //计算重复的内容
        while (letterIndex < str.length) {
    
    
            if (!/[a-zA-Z]/.test(str[letterIndex])) break
            item += str[letterIndex]
            letterIndex++
        }
        for (let i = 0; i < num; i++) {
    
    
        	//拼接成对应格式
            if (i === 0) {
    
    
                res = item + target
            } else {
    
     //进行总体内容重复
                res = item + target + res
            }
        }
        target = res
        str = str.slice(0, index)
    }
    return res
}

猜你喜欢

转载自blog.csdn.net/weixin_44523860/article/details/114546799