首页 > 代码库 > 40.@返回字符串中出现次数最多的那个字符和次数2

40.@返回字符串中出现次数最多的那个字符和次数2


技术分享
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>@返回字符串中出现次数最多的那个字符和次数2</title>
 6 
 7 </head>
 8 <body>
 9 </body>
10 
11 <script type="text/javascript">
12     //将字符串的字符保存在一个hash table中,key是字符,value是这个字符出现的次数
13     var str = "eeefffgh";
14     var obj = {};
15     for (var i = 0, l = str.length; i < l; i++) {
16         var key = str[i];
17         if (!obj[key]) {
18             obj[key] = 1;
19         } else {
20             obj[key]++;
21         }
22     }
23 
24     /*遍历这个hash table,获取value最大的key和value*/
25     var max = -1;
26     var max_key = "";
27     var key;
28     for (key in obj) {
29         if (max < obj[key]) {
30             max = obj[key];
31             max_key = key;
32         }
33     }
34 
35     console.log("max:" + max + " max_key:" + max_key); //max:3 max_key:e
36 </script>
37 </html>
View Code


<!DOCTYPE html>

<html>
<head lang="en">
<meta charset="UTF-8">
<title>@返回字符串中出现次数最多的那个字符和次数2</title>

</head>
<body>
</body>

<script type="text/javascript">
//将字符串的字符保存在一个hash table中,key是字符,value是这个字符出现的次数
var str = "eeefffgh";
var obj = {};
for (var i = 0, l = str.length; i < l; i++) {
var key = str[i];
if (!obj[key]) {
obj[key] = 1;
} else {
obj[key]++;
}
}

/*遍历这个hash table,获取value最大的key和value*/
var max = -1;
var max_key = "";
var key;
for (key in obj) {
if (max < obj[key]) {
max = obj[key];
max_key = key;
}
}

console.log("max:" + max + " max_key:" + max_key); //max:3 max_key:e
</script>
</html>

40.@返回字符串中出现次数最多的那个字符和次数2