Created
May 25, 2014 16:20
-
-
Save jikeytang/986b745fa81087d0a225 to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140526-题目2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
查找字符串中出现最多的字符和个数。 | |
如: addfbsdfaf,字母d出现的次数最多,且为4次。 | |
PS: | |
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。 | |
```javascript | |
// you code | |
``` | |
2. 粘贴代码时请使用shift+tab,缩进前面的空白。 |
rambo-panda
commented
May 26, 2014
function getCharAndCount(str){
var len = str.length; i = 0, lenArr = [], max = 0;
while(i < len){
lenArr.push({n: str.split(str[i]).length - 1, c: str[i++]});
}
max = lenArr.sort(function(a, b){return b.n - a.n;})[0];
return {char: max.c, count: max.n};
}
getCharAndCount("ababbc"); // {char: "b", count: 3}
@mailzwj 方法 多次使用split 以及 str[i++] 多次隐式转换成Array再进行取值。 对长数据 不会有影响吗?
ES5的forEach
function test(arr){
var uniqArr = [];
var obj = {};
arr.forEach(function(item){
if(uniqArr.indexOf(item) == -1){
uniqArr.push(item);
obj[item] = 1;
} else {
obj[item] ++;
}
});
uniqArr.sort(function(a, b){
return obj[b] - obj[a];
});
return {
str: uniqArr[0],
num: obj[uniqArr[0]]
};
}
console.log(test("addfbsdfaf".split("")));
function a (a) {
var x, y, z;
for(var i = 0; i < a.length; i++){
y = a.split(a[i]).length;
if(!x || y > x){
x = y;
z = a[i];
}
}
return {
str : z,
length : x
}
}
function getStrMore2(str){
var getStr,
oldStr,
res = {},
max = 0;
while(str){
getStr = str.slice(0,1);
oldStr = str;
str = str.replace(new RegExp(getStr, 'g'), '');
if(max < oldStr.length - str.length){
max = oldStr.length - str.length;
res['target'] = getStr;
res['max'] = max;
}
}
return res;
}
getStrMore2('addafsfe');
@zjhsd2007 字符串太长的话 sort效率好低
var str = 'addfbddsdfaf';
var nStr = str.split('').sort().join('');
var re = /(\w)\1*/g; //
var tempArr = nStr.match(re), temp = 0 ,index = 0;
for(var i =0; i < tempArr.length ; i ++){
if( tempArr[i].length > temp){
temp = tempArr[i].length ;
index = i ;
}
}
console.log( '字母'+tempArr[index][0]+'出现的最多,you'+temp+'次' )
@ljkfgh2008 你的好像有问题
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment