HNQ
HNQ

Reputation: 110

Improve code check frequency of character in a string

I wrote this code today to check frequency of each character in string. It runs quite slowly. How can I improve this code ?

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");
    }
}

Upvotes: 0

Views: 1085

Answers (1)

Jigar Joshi
Jigar Joshi

Reputation: 240956

Use HashMap to map Character to the Occurance (Integer)

Upvotes: 1

Related Questions