整理下初学时做过的js基础编程题目和大家分享以下,如果大家觉得有用,别忘了点一下赞哦
字符串中出现最多的字符
请找出下列字符串出现最多的字符和次数
let str = "abacaaabcbc"
第一种方法:map(哈希表)
function test(str){
let map = new Map()
let maxCount = 0;
let maxStr
for(let i = 0;i<str.length;i++){
if(map.has(str[i])){
map.set(str[i],map.get(str[i]) + 1)
}else{
map.set(str[i],1)
}
}
for(let [i,ch] of map.entries()){
console.log(i,ch)
if(maxCount < ch){
maxCount = ch
maxStr = i
}
}
return `最大值${maxStr},最大次数${maxCount}`
}
第二种方法:对象
function test(str) {
let obj = {}
let strArr = str.split("")
let maxCount = 0;
let maxStr;
strArr.forEach((val, i) => {
if (obj[val]) {
obj[val]++
} else {
obj[val] = 1
}
})
for (let key in obj) {
if (obj[key] > maxCount) {
maxCount = obj[key]
maxStr = key
}
}
return `最大值${maxStr},最大次数${maxCount}`
}