javascript-----常见算法整理

11 篇文章 1 订阅
6 篇文章 0 订阅
  1. 字符串反转
    因为这个是用的自己的最简单的方法进行的实现,所以不整理代码了
  2. 回文(正着读与反着读效果一样,称为回文)
    思路:利用数组的reverse方法,join方法进行拼接,判断反转后拼接是否与原数据一致,一致则是回文
  3. 出现次数最多的字符
    思路:创建一个对象,然后遍历字符串,字符串的每个字符作为对象的key,value是对应该字符出现的次数。然后我们可以遍历这个对象,找出value最大的key
	const maxCharacter = (str) => {
	    const obj = {}
	    let max = 0
	    let character = ''
	    for (let index in str) {
	      obj[str[index]] = obj[str[index]] + 1 || 1
	    }
	    for (let i in obj) {
	      if (obj[i] > max) {
	        max = obj[i]
	        character = i
	      }
	    }
	    return character
	  }
  1. 找出string中元音字母出现的个数
    思路:利用正则表达式提取所有的元音,然后统计。利用数组的includes方法,但是首先输入的参数转为小写
  const vowels = str => {
    const choices = ['a', 'e', 'i', 'o', 'u']
    let count = 0
    for (let character in str) {
      if (choices.includes(str[character])) {
        count ++
      }
    }
    return count
  }

//match 返回的是字符串类型,返回匹配到的信息内容
  const vowelsRegs = str => {
    const match = str.match(/[aeiou]/gi)
    return match ? match.length : 0
  }
  1. 数组分隔
    思路:通过熟路的slice进行截取,利用while进行循环按给定大小的步骤递增
const chunk = (array, size) => {
  const chunks = []
  let index = 0
   while(index < array.length) {
     chunks.push(array.slice(index, index + size))
     index += size
   }
   return chunks
}
  1. 首字母大写
    思路:指定位置的字符进行大写,然后拼接截取指定位置开始的剩余的字符
const capitalize = str => {
  return str.split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ')}
  1. 凯撒密码(百度具体意思)
const caesarCipher = (str, number) => {
  const alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
    const string = str.toLowerCase()
    const remainder = number % 26
    let outPut = ''
    for (let i = 0; i < string.length; i++) {
      const letter = string[i]
      if (!alphabet.includes(letter)) {
        outPut += letter
      } else {
        let index = alphabet.indexOf(letter) + remainder
        if (index > 25) {
          index -= 26
        }
        if (index < 0) {
          index += 26
        }
        outPut += str[i] === str[i].toUpperCase() ? alphabet[index].toUpperCase() : alphabet[index]
      }
    }
  return outPut
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值