js实战之-求一个字符串中最多出现的字符数

昨天有一个网友问我一个问题,就是怎么样求一个字符串中最多出现的字符数。我想了想感觉这个问题的解决方法挺多的,于是我就写了一个给他做参考,如有什么问题还请广大网友朋友指正:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>

</body>

<script>
var str="thfsggggggggghjhjghjghjhgjjjjjjjjjjjjjjjjjjgfgrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr";
var obj={};
var arr=[];
var maxnum=0;
var strLen;
for(var i=0;i<str.length;i++){
	 var t=str.charAt(i);
	  if(!obj[t]){
		   obj[t]=1;  	
	  }else{  
		 obj[t]+=1;  	  
	  }  
	  if(obj[t]>maxnum){
		   maxnum=obj[t];  
		   strLen=t;
	  }

}


alert("出现最多的是"+strLen+"出现了:"+maxnum+"次");


</script>
</html>

 下面这个是在网上看到的一种方法:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>无标题文档</title>
 6 </head>
 7 
 8 <body>
 9 
10 </body>
11 
12 <script>
13 var str="asdfjksggggggggggggggggggggggggdjfljsdflkffffffffffdfdfdfdffffffffffffffffffffffffffffffjsdjf";
14 var maxnum=0;
15 var res=null;
16 while(str!=""){
17     var oldLen=str.length;
18     var news=str.substr(0,1);
19     str=str.replace(new RegExp(news,"g"),"");
20     var newLen=str.length;
21     if(oldLen-newLen>maxnum){    
22          maxnum=oldLen-newLen;    
23          res=news;
24     }
25     
26 }
27 
28 alert("出现最多的是"+res+"共出现了:"+maxnum+"次");
29 </script>
30 </html>

 

 

posted @ 2013-08-09 09:42  梦飞无颜  阅读(318)  评论(0编辑  收藏  举报