Bản in của bài viết

Click vào đây để xem bài viết này ở định dạng ban đầu

lehuy0305's Blog

CountChar.java

import java.util.ArrayList;

public class CountChar {

    public static void main(String[] args) {
        String s = "Dien Dan JavaVietNam".toUpperCase();
        ArrayList<Character> val = new ArrayList<Character>(); // ArrayList char ch?a các char trong String
        boolean flag = true;
        for (int x = 0; x < s.length(); x++)
            if (val.size() == 0)
                val.add(s.charAt(x));//gán char d?u tiên
            else {
                flag = true;
                for (int y = 0; y < val.size(); y++) {
                    if (val.get(y) == s.charAt(x)) {
                        flag = false;
                        continue;
                    }
                }
                if (flag)
                    val.add(s.charAt(x));//gán các char ti?p theo, l?c l?i khi trùng.
            }
        int max = 0, tmp = 0;
        int[] count = new int[val.size()]; //m?ng int d?m s? l?n char xu?t hi?n
        for (int x = 0; x < val.size(); x++) {
            tmp = 0;
            for (int y = 0; y < s.length(); y++)
                if (val.get(x) == s.charAt(y))
                    tmp++;// d?m s? l?n xu?t hi?n
            if (max < tmp)
                max = tmp;//tìm l?n max
            count[x] = tmp;//gán s? l?n xu?t hi?n
        }

        for (int x = 0; x < val.size(); x++)
            System.out.println("Ky tu : " + val.get(x) + " xuat hien " + count[x] + " lan");
        for (int x = 0; x < val.size(); x++)
            if (count[x] == max)
                System.out.println("Ky tu : " + val.get(x) + " xuat hien nhieu nhat , voi " + count[x] + " lan");

    }
}

VnVista I-Shine
© http://vnvista.com