Created
June 13, 2017 06:48
-
-
Save ninan1028/572be4a0e5f94759146fcf7cdf3daf3d to your computer and use it in GitHub Desktop.
得到字符串中出现次数最多的字符及个数
This file contains 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
// 使用普通 的方法 | |
var str="assssfdererdsdsgseres"; | |
function method1(){ | |
var str=document.getElementById("J_input").value; | |
if(str){ | |
var obj={}; | |
var num=0; | |
var value=0; | |
var length=str.length; | |
for(var i=0;i<length;i++){ | |
if(!obj[str.charAt(i)]){ | |
obj[str.charAt(i)]=[]; | |
} | |
obj[str.charAt(i)].push(obj[str.charAt(i)]) | |
} | |
for(v in obj){ | |
if(num<obj[v].length){ | |
num=obj[v].length; | |
value=v; | |
} | |
} | |
alert(value+":"+num); | |
} | |
} |
This file contains 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
function method2(){ | |
var str=document.getElementById("J_input").value; | |
if(str){ | |
var num=0; | |
var value=0; | |
var attr=str.split("").sort(); | |
var newstr=attr.join(""); | |
var reg=/(.)(\1)+/g; | |
newstr.replace(reg,function($0,$1){ | |
if(num<$0.length){ | |
num=$0.length; | |
value=$1; | |
} | |
}) | |
alert(value+":"+num); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment