Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีหาตัวอักษรที่เกิดบ่อยที่สุดใน String ด้วย Java


String ใช้แทน สตริงอักขระ ทุกตัวอักษรใน Java เป็นอินสแตนซ์ของคลาส String String เป็นค่าคงที่ immutable ไม่สามารถเปลี่ยนค่าได้หลังสร้างแล้ว

ในโปรแกรมนี้ เราจะหา ตัวอักษรที่เกิดบ่อยที่สุด (maximum occurred character) ของสตริงที่กำหนด

ตัวอย่าง

public class MaxOccuredCharacterTest {
    public static void main(String[] args) {
        String str1 = maxOccuredChar("tutorialspoint");
        System.out.println(str1);
        String str2 = maxOccuredChar("AABBAABBCCAABBAA");
        System.out.println(str2);
        String str3 = maxOccuredChar("111222333444333222111");
        System.out.println(str3);
    }

    public static String maxOccuredChar(String str) {
        char[] array = str.toCharArray();
        int maxCount = 1;
        char maxChar = array[0];
        for(int i = 0, j = 0; i < str.length() - 1; i = j) {
            int count = 1;
            while(++j < str.length() && array[i] == array[j]) {
                count++;
            }
            if (count > maxCount) {
                maxCount = count;
                maxChar = array[i];
            }
        }
        return (maxChar + " = " + maxCount);
    }
}

ผลลัพธ์

t = 1 A = 2 1 = 3