1. 程式人生 > 其它 >演算法基礎提升——隨機池結構問題、布隆過濾器、一致性Hash演算法、島問題、並查集實現

演算法基礎提升——隨機池結構問題、布隆過濾器、一致性Hash演算法、島問題、並查集實現

import java.util.ArrayList;
import java.util.Scanner;

public class Javatest76 {
    /**
     * 筆試題
     * 練習2:輸入一個字串,輸出出現次數最多的前2個字元及出現次數
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入一個字串:");
        String s = sc.nextLine();
        test(s);
    }
    
//統計字串中每個字元出現次數 public static void test(String s){ char[] arr = s.toCharArray(); ArrayList<Character> list = new ArrayList<>(); int[] count = new int[26]; //出現次數最多的兩個字母出現的次數 int max1 = 0; int max2 = 0; //出現次數最多的兩個字元 char max1c = 'a';
char max2c = 'a'; //統計字串中每個字元出現的次數 for (int i = 0; i < arr.length; i++) { if(!list.contains(arr[i])){ //記錄字元出現的順序 list.add(arr[i]); } count[arr[i] - 'a']++; //出現次數多於當前最多的次數 if(count[arr[i] - 'a'] >= max1){
if(arr[i] != max1c){ max2 = max1; max2c = max1c; max1c = arr[i]; } max1 = count[arr[i] - 'a']; } //出現次數多於當前出現次數第二多的 else if(count[arr[i] - 'a'] > max2){ max2 = count[arr[i] - 'a']; max2c = arr[i]; } } //出現次數最多的多餘兩個字元時,控制僅輸出前兩個 int time = 0; for (int i = 0; i < list.size(); i++) { if((count[list.get(i) - 'a'] == max1 || count[list.get(i) - 'a'] == max2) && time < 2){ System.out.println(list.get(i) + "出現次數:" + count[list.get(i) - 'a']); time++; } } } }