每日一道算法题——求xx字母个数,用正则处理文本是很方便的

每日一道算法题

  1. 输入一段字符串,求元音字母(a,e,i,o,u)的个数

    function getCount(str) {
       let vowelCount = 0
       for (let i = 0; i < str.length; i++) {
           if(str[i] === 'a' || str[i] === 'e' || str[i] === 'i' || str[i] === 'o' || str[i] === 'u') {
               vowelCount++
           }
       }
       return vowelCount
    }

排名靠前的答案:

function getCount(str) {
    return (str.match(/[auiou]/ig) || []).length
}
const getCount = str => str.replace(/[^aeiou]/ig, '').length

题目:Array.diff

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

It should remove all values from list a, which are present in list b.

array_diff([1,2],[1]) == [2]

If a value is present in b, all of its occurrences must be removed from the other:

array_diff([1,2,2,2,3],[2]) == [1,3]

my answer:

function array_diff(a, b) {
    let tmp = []
    for (let i = 0; i < a.length; i++) {
        for (let j = 0; j < b.length; j++) {
            if (a[i] == b[j]) continue
             else tmp.push(a[i])
        }
    }
}

初步测试通过,提交测试的时候代码错误,这样会导致,其中一个有重复的数组也会被当做不同输出 a[1,1,2,3] b[2, 3] 这样会输出 arrar_diff == [1,1]

改进:

function array_diff(a, b) {
    return a.filter(v => !(b.indexOf(v) > -1))
}

排行榜答案:

function array_diff(a, b) {
    return a.filter(v => b.indexOf(v) == -1)
}

题目:Friend or Foe?

function friend(friends) {
    let tmp = []
    for (let i = 0; i < friends.length; i++) {
        if (friends[i].length === 4) {
            tmp.push(friends[i])
        }
    }
}
function friend(friends){
  return friends.filter(n => n.length === 4)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值