zoukankan      html  css  js  c++  java
  • js

    方法一:

      /**
           * @param {String}str 只接受字符串类型
           * @return{JSON} key:出现最多字符, value:出现次数;  数组类型不是String类型,则返回空对象
           **/
        function getMax(str){
        	let hash = {};
        	let num = 0;
        	let json = {}; //返回的对象
        	//判断是否是字符串
        	if(Object.prototype.toString.call(str) != "[object String]") {
        		return json;
        	}
        	for(let i = 0; i < str.length; i++){
        		if(hash[str[i]] === undefined){
        			hash[str[i]] = 1
        		}else{
        			hash[str[i]]++
        		}
        	}
        	for(let item in hash){
        		if(num < hash[item]){
        			num = hash[item]
        			json = {"字符": item, "次数": hash[item]}
        		}
        	}
        	return json;
        }
    

    方法二:

    function getMax(str){
           	 let obj = {};
           	 let num = 0;
           	 let letter = '';
           	 for(let i = 0; i < str.length; i++){
           	 	if(obj[str[i]]){
           	 		obj[str[i]]++;
           	 		if(num < obj[str[i]]){
           	 			num = obj[str[i]];
           	 			letter = str[i]
           	 		}
           	 	}else{
           	 		obj[str[i]] = 1;
           	 	}
           	 }
           	 
           	 return letter + ':' + num
           }
    

    方法三:

    var s = 'aaabbbcccaaabbbaaabbbbbbbbbb';
    	   var a = s.split('');
    	   a.sort();
    	   s = a.join('');
    	   var pattern = /(w)1*/g;
    	   var ans = s.match(pattern);   
    	   ans.sort(function(a, b) {
    	       return b.length - a.length;
    	    });
    	   console.log(ans);
    	   console.log(ans[0][0] + ': ' + ans[0].length);
    
  • 相关阅读:
    背水一战 Windows 10 (26)
    背水一战 Windows 10 (25)
    背水一战 Windows 10 (24)
    背水一战 Windows 10 (23)
    背水一战 Windows 10 (22)
    背水一战 Windows 10 (21)
    背水一战 Windows 10 (20)
    背水一战 Windows 10 (19)
    背水一战 Windows 10 (18)
    背水一战 Windows 10 (17)
  • 原文地址:https://www.cnblogs.com/sunidol/p/11512458.html
Copyright © 2011-2022 走看看