当前位置: 首页 > 面试经验 >

8.31华为机试 第一题字符串压缩 JavaScript

优质
小牛编辑
150浏览
2023-03-28

8.31华为机试 第一题字符串压缩 JavaScript

//前后华为给的代码我忘了,直接写核心

//处理句子和字典
var sentence = inputArrays[0].split(" ")
var dictionary = inputArrays[1].split(" ")
//大小写不敏感,把字典全改大写,句子里面有特殊字符,改不了
dictionary = Array.from(dictionary,item=>item.toUpperCase())
//处理引号内的,思路是定义一个开关。当时引号单词忘了咋拼。。
var isInside = false
for(let i in sentence){
    if(sentence[i]=='"'){
        isInside = !isInside    //开关
        continue    //引号不进行字典查询
    }
    var str = sentence[i].replace(/[^a-zA-Z]/,"")
    //含有特殊字符的话toUpperCase()会报错,在这里卡了蛮久,属于是考场上学知识了
    if(dictionary.includes(str.toUpperCase())){
        //之前用for循环倒序查字典的,过80%,剩下的超时,所以优化,先查有没有
        var j = sentence[i] = dictionary.lastIndexOf(str.toUpperCase())
        //最后的索引,当然lastIndexOf()
        str.length==sentence[i].length? sentence[i]=j:sentence[i]=j+sentence[i][sentence[i].length-1]
        //通过对比长度来看有没有句号逗号,有的话取过来
    }
}
console.log(sentence.join(" "))
仅分享一下自己的解法,记录自己笔试以来的第一次A。
非科班8月才开始刷算法,每次都遇到矩阵,每次都不会做,第二题直接0,爆哭
 类似资料: