You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
letstr='Once you learn to quit, it becomes a habit.'const出现最多的字符以及次数=str=>{let记录出现次数最多的字符=str[0],字符映射={}for(letsofstr){if(s==' ')continues=s.toLowerCase()字符映射[s]=字符映射[s] ? 字符映射[s]+1 : 1记录出现次数最多的字符=字符映射[记录出现次数最多的字符]>字符映射[s] ? 记录出现次数最多的字符 : s}return[记录出现次数最多的字符,字符映射[记录出现次数最多的字符]]}console.log(出现最多的字符以及次数(str))
function getMostChar(str){
let i = 0
let obj = {}
while(i<str.length){
let c = str.charAt(i)
if(obj.hasOwnProperty(c)){
obj[c]+=1
}else{
obj[c]=1
}
i++
}
let maxValue = 0
let res = {}
for(let key in obj){
if(obj[key]>maxValue){
res={}
maxValue = obj[key]
res[key] = obj[key]
}else{
if(obj[key]==maxValue){
res[key] = obj[key]
}
}
}
return res
}
console.log(getMostChar('aaansbsdddksda'))
Activity
ohion commentedon Nov 10, 2020
sisterAn commentedon Nov 11, 2020
再补充一种:使用正则
mingju0421 commentedon Nov 11, 2020
cutie6 commentedon Nov 13, 2020
需要对正则的数字引用非常熟悉才能想到这种解法吧
laiyingzeng commentedon Jul 6, 2021
for 循环 i 应该从 0 开始
NoBey commentedon Mar 23, 2022
AlexZhang11 commentedon May 24, 2024
function getMostChar(str){ let i = 0 let obj = {} while(i<str.length){ let c = str.charAt(i) if(obj.hasOwnProperty(c)){ obj[c]+=1 }else{ obj[c]=1 } i++ } let maxValue = 0 let res = {} for(let key in obj){ if(obj[key]>maxValue){ res={} maxValue = obj[key] res[key] = obj[key] }else{ if(obj[key]==maxValue){ res[key] = obj[key] } } } return res } console.log(getMostChar('aaansbsdddksda'))