查找一個字符串出現最多,並計算其次數

public class Main {

    public static void main(String[] args) {
        String str = "aabbccdd";//字符串
        char[] chars =str.toCharArray();//轉化爲數組
        int count = 0;
        int countTemp = 0;
        char findStr=0;
        int length = chars.length;
        char[] newChars = SetChars(str);//去重 傳入字符串
        for(int i=0;i<newChars.length;i++){
            char tempStr = newChars[i];
            for (int j=0;j<length;j++){
                if(tempStr==chars[j]){
                    countTemp++;
                }
                if(j==(length-1)) {
                    if (countTemp > count) {
                        count = countTemp;
                        findStr = tempStr;
                    }
                    countTemp = 0;
                    System.out.println("出現字符是:"+tempStr+",次數是:"+count);
                }
            }
        }
        System.out.println("出現最多的字符是:"+findStr+",次數是:"+count);
    }
    //去重
    private static char[] SetChars(String s){
        if (s == null)
            return s.toCharArray();
        StringBuilder sb = new StringBuilder();
        int i = 0, len = s.length();
        while (i < len) {
            char charAt = s.charAt(i);
            sb.append(charAt);
            i++;
            while (i < len && s.charAt(i) == charAt) {
                i++;
            }
        }
        return sb.toString().toCharArray();
    }
}

發佈了29 篇原創文章 · 獲贊 11 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章