查找字符串中出现最多的字符

方法一:利用js的split和join方法

 1 function foo(str){
 2     var max = 0;
 3     var char = []; // 存放出现次数最多的字符
 4     while(str){
 5         var head = str.charAt(0);
 6         var arr = str.split(head);
 7         var num = str.length - arr.join('').length;
 8         if(num > max){
 9             max = num;
10             char.length = 0;
11             char.push(head);
12         }else if(num === max){
13             char.push(head);
14         }
15         str = arr.join('');
16     }
17     return {maxNum:max,chars:char};
18 
19 }

方法二:此处要用对象key查找而不是用下标遍历,前者时间是1后者是n

 1 function foo(str){
 2     let result = [];
 3     for(let i = 0; i < str.length; i++){
 4         if(result[str[i]]){
 5             result[str[i]] += 1;
 6         }else{
 7             result.push(str[i]);
 8             result[str[i]] = 1;
 9         }
10     }
11 
12     let max = 0;
13     let char = [];
14     for(let key in result){
15         if(result[key] > max){
16             char.length = 0;
17             max = result[key];
18             char.push(key);
19         }else if(result[key] === max){
20             char.push(key);
21         }
22     }
23 
24     retrun {maxNum:max,chars:char};
25 
26 }

 

posted @ 2018-04-17 20:06  BarneyWhite  阅读(679)  评论(0编辑  收藏  举报