判断字符串中出现次数最多的字符和出现次数

package my;

import java.util.HashMap;

public class FindStringMaxSolution {
    int findStrMax(String str){
        if(str.length() == 0 || str == null){
            return -1;
        }
        int max =0;
        HashMap<Character , Integer> map = new HashMap<>();
        for(int i= 0 ; i < str.length() ; i++){
            char c = str.charAt(i);
            if(map.containsKey(c)){
                map.put(c ,map.get(c)+1);
            }else{
                map.put(c,1);
            }
        }

for(int j=0 ;j <str.length(); j++){ max = Math.max(max ,map.get(str.charAt(j))); } return max; } public static void main(String[] args){ String str ="3w3wrr3rk3jr"; int n = new FindStringMaxSolution().findStrMax(str); System.out.println(n); } }
package my;

import java.util.HashMap;

public class FindStringMaxSolution {
    int findStrMax(String str){
        if(str.length() == 0 || str == null){
            return -1;
        }
        int max =0;
        char charmax = 0;
        HashMap<Character , Integer> map = new HashMap<>();
        for(int i= 0 ; i < str.length() ; i++){
            char c = str.charAt(i);
            if(map.containsKey(c)){
                map.put(c ,map.get(c)+1);
            }else{
                map.put(c,1);
            }
        }
        for(char key : map.keySet()){
            if(map.get(key) > max){
                max = map.get(key);
                 charmax = key;
            }
        }
        System.out.println(charmax);
        return max;
    }
    public static void main(String[] args){
        String str ="3w3wrr3rk3jr";
        int n = new FindStringMaxSolution().findStrMax(str);
        System.out.println(n);
    }
}

 

posted on 2020-09-14 02:08  凌晨三点半的飞机  阅读(184)  评论(0编辑  收藏  举报