Front-end interview - several algorithm questions about strings

1. Given a number, the returned result is every three numbers plus a comma, such as 100000, the returned result is 100,000

function toThousands(number){
    numArr = number.toString().split('')
    let counter = 0
    const arr = []
    numArr.forEach((item,index) => {
        counter++        
        counter % 3 == 0 && index !== numArr.length-1 ? arr.push(item,',') : arr.push(item)
    })
    return arr.join('')
}

2. Given a string, output the maximum length without repeated characters

// 滑动窗口
// 设置左右两个指针,右指针一直向右扩张,当不满足条件时,左边指针开始收缩,直到再次满足条件,之后右指针继续扩张

function lengthOfLongestSubstring (s) {
    let count=0;
    let set=new Set();
    //左指针用来收缩窗口
    let left=0;
    //右指针用来扩张窗口
    let right=0;
    while(left<s.length){
        //如果不重复,就不断扩张窗口,元素添加到set中
        while(right<s.length&&!set.has(s[right])){
            set.add(s[right]);
            right++;
        }
        //元素重复了,先记录子串长度,然后收缩窗口
        count=Math.max(count,right-left);
        //收缩窗口
        set.delete(s[left]);
        left++;
    }
        return count;
}

3. Given a string, output the maximum number of characters and times in the string

function maxLetter(str){
    var obj = {}
    for(let i = 0; i < str.length; i++){
        if(!obj.hasOwnProperty(str[i])){
            obj[str[i]] = 1
        }else{
            obj[str[i]]++
        }
    }
    let maxKey,maxNumber = 0
    for(let key in obj){
        if(maxNumber < obj[key]){
            maxNumber = obj[key]
            maxKey = key
        }
    }
    return `最大的字符是${maxKey},出现的次数为${maxNumber}` 
}

4. Save the parameters in the url address bar into the object and output the object

function getUrlParams(url){
  const Params = {}
  if(url.indexOf('?')>0){//判断是否有qurey
    let parmas = url.slice(url.indexOf('?')+1)//截取出query
    const paramlists = parmas.split('&')//分割键值对
    for (const param of paramlists) {
      let a = param.split('=')
      Object.assign(Params,{[a[0]]:a[1]})//将键值对封装成对象
    }
  }
  return Params
}

Guess you like

Origin blog.csdn.net/weixin_51382988/article/details/129732020