每日一道算法题
输入一段字符串,求元音字母(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)
}