leetcode Day10

63 阅读1分钟

面试题 01.03. URL化

var replaceSpaces = function(S, length) {
    let s=S.split('')
    for(let i=0;i<length;i++){
        if(s[i]===' '){
            s[i]='%20'
        }
    }
    return s.join('').trim()
};

面试题 01.04. 回文排列

think-out-loud:用哈希表存储每个字符出现次数,只允许一个字符出现奇数次

var canPermutePalindrome = function(s) {
    let mp=new Map()
    let c=0
    for(let i of s){
        mp.set(i,mp.has(i)?mp.get(i)+1:1)
    }
    for(let [key,value] of mp){
        if(value%2!==0){
            c++
        }
    }
    if(c>1){return false}
    return true
};

面试题 01.05. 一次编辑

think-out-loud:用双指针一起移动,给一次修改机会(不一致的机会),超过一次就false

var oneEditAway = function(first, second) {
    if(Math.abs(first.length-second.length)>1){
        return false
    }
    if(first===second){return true}
    let f=0,s=0
    let flag=false
    while(f<first.length && s<second.length){
        if(first[f]===second[s]){
            f++
            s++
        }else{
            if(!flag){
                if(first.length===second.length){
                    f++
                    s++
                }
                else if(first.length>second.length){
                    f++
                }else{
                    s++
                }
                flag=true
            }
            else{
                return false
            }
        }
    }
    return true
};