改进代码检查字符串中字符的频率

时间:2012-01-31 03:25:54

标签: java

我今天编写了这段代码来检查字符串中每个字符的频率。它运行得很慢。如何改进此代码?

import java.util.*;
public class checkFreq {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        // Input
        System.out.print("Enter a string: ");
        String input = s.nextLine();
        long t1 = System.currentTimeMillis();
        // Convert input to UpperCase
        String tmp = input.toUpperCase();

        // String to compare 
        String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int aleng = alphabet.length();

        for (int l = 0; l < aleng; l++) {
            //Run 26 times
            int count = 0;
            int i = 0;
            String tmp2;
            while (i < tmp.length() - 1) {
                tmp2 = tmp.substring(i, i + 1);
                int exist = tmp2.indexOf(alphabet.charAt(l));
                if (exist != -1) {
                    count++;
                }
                i++;
            }//End while

            if (count != 0) {
                System.out.print(alphabet.charAt(l) + "(" + count + ") ");
            }//End if
        }// End for
        System.out.println();

        long t2 = System.currentTimeMillis();
        // Count time of process
        System.out.println("Time : " + (t2 - t1) + "ms");
    }
}

1 个答案:

答案 0 :(得分:1)

使用HashMapCharacter映射到事件(Integer