const str = 'aaasdofjaopfjopaiiisjssfopiasdfffff';
/*--------- '连续' 出现最多的字母及出现的次数 ------*/
function findRepeat(str){
const arr = str.match(/(.)\1+/g)
let [maxKey,max] = ['',0]
arr.map(item => {
if(item.length > max){
maxKey = item[0];
max = item.length;
};
});
return {maxKey,max}
};
const res = findRepeat(str)
console.log('连续出现次数最多的是'+ res.maxKey +'出现了'+ res.max +'次数')
/*--------- 出现最多的字母及出现了多少次 ------*/
function findRepeat(str){
let [maxKey,max,obj] = ['',1,{}];
for(var i=0;i<str.length;i++){
obj[str[i]] = obj[str[i]] ? ++obj[str[i]] : 1;
if(obj[str[i]] > max){
max = obj[str[i]]
maxKey = str[i]
};
}
return {maxKey,max}
}
const res = findRepeat(str)
console.log('出现次数最多的是'+ res.maxKey +'出现了'+ res.max +'次数')
/*--------- 任意一个出现两次以上的字母及出现了多少次 ------*/
function findRepeat(str){
let obj = {};
for(var i=0;i<str.length;i++){
obj[str[i]] = obj[str[i]] ? ++obj[str[i]] : 1
if(obj[str[i]] > 2){
return [str[i],obj[str[i]]]
}
}
}
const res = findRepeat(str);
console.log(res[0] +'出现了'+ res[1] +'次数')
来源:CSDN
作者:weixin_39107093
链接:https://blog.csdn.net/weixin_39107093/article/details/98735828