每日思考之编程题,找出字符串中连续出现最多的字符和个数(蘑菇街)

it2024-07-30  72

思路 :

先把字符串切割成数组,然后进行遍历。定义一个变量来保存前一个字符,对象来保存每个字符以及它出现的次数遍历对象,返回连续出现最多的字符和个数 function findMax(str = '') { let obj = {},arr = [...str],current='',max=0; for (let i=0,len=arr.length; i<len; i++){ if(current === arr[i]){ obj[arr[i]] +=1; }else { current=arr[i]; obj[arr[i]] =obj[arr[i]]?obj[arr[i]]:1;//如果已经存在,就保留原来的值,以免覆盖 } } for(item in obj){ if(obj[item] > max){ max = obj[item]; current =item; } } return {current,max}; } console.log(findMax('aaaaavvvasdasdasdasfasf'));

 

最新回复(0)