qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.14k stars 95 forks source link

Day384:用二分法移除一个字符串中的所有字母字符?(腾讯) #387

Open qappleh opened 3 years ago

guanxc9876 commented 3 years ago

移出字符串的字母为啥还得要二分法。。。

guanxc9876 commented 3 years ago
getValue() {
  const valList = []
  function handleLetter(str, idx) {
    if ((str[idx] >= 'a' && str[idx] <= 'z') || (str[idx] >= 'A' && str[idx] <= 'Z')) {
      valList.push(idx)
    }
  }
  function handle(str, direction = null, val = 0) {
    let low
    let high
    if (direction === 'left') {
      low = 0
      high = val - 1
    } else {
      low = val
      high = str.length - 1
    }

    if (low > high) return
    const mid = Math.floor((low + high) / 2)
    if (mid === low === high) return
    handleLetter(str, mid)
    if (mid === val) return
    if (mid + 1 === str.length - 1) {
      handleLetter(str, mid + 1)
      return
    }
    console.log('=====')
    if (Number(valList.length) === Number(str.length)) {
      [...new Set(valList)]
      console.log('valList', JSON.parse(JSON.stringify(valList)))
      return
    }
    (function(i) {
      setTimeout(function() {
        handle(str, 'right', i)
        handle(str, 'left', i)
      }, 0)
    })(mid)
  }
  handle('1a2b3d4e5f6g7h8i9j')
  console.log('===aaaaaaaaaaaaaaaaaaa====', valList)
},

废了,获取字母下标陷入死循环,还能不能抢救下