从字符串计算字符的频率而不使用Collection?

时间:2014-08-10 08:22:44

标签: java

任何人都可以帮我解决这个问题吗?

鉴于:

String s =" aasbkllzzzs&#34 ;;

预期输出:

代表

的东西
   a has count 2
   s has count 2
   l has count 2
   z has count 3

试过这个,但我认为不正确,任何人都帮我修改这个答案.... **

    int[] count = new int[256];
      for(int ch; (ch = "aasbkllzzzs") >= ' ';)  //type mismatch exception,help me plz
          count[ch]++;
      for(char ch = 0; ch < count.length; ch++)
          if (count[ch] > 0)
              sysOut(ch + " appears " + count[ch] + " times");

寻找可以用5行代码给出答案的人.. 因为我的面试官想要用5行代码回答

3 个答案:

答案 0 :(得分:4)

class Main {
    public static void main(String[] args) {
        String str = "aasbkllzzzs";

        // create frequency table for 128 - ASCII Characters
        int[] freq = new int[128];

        // For each character, increment count in the frequency table
        for (char ch : str.toCharArray()) {
            freq[ch]++;
        }

        System.out.println("Frequencies : ");
        for (int i = 0; i < freq.length; i++) {
            // Print results for which count > 0
            // (char) i => Character
            // freq[i] => Frequency of character
            if (freq[i] != 0) {
                System.out.println("Char : " + (char) i + ", Count : "
                        + freq[i]);
            }
        }
    }
}

输出:

Frequencies : 
Char : a, Count : 2
Char : b, Count : 1
Char : k, Count : 1
Char : l, Count : 2
Char : s, Count : 2
Char : z, Count : 3

答案 1 :(得分:0)

在5行代码中:

public class CountCharacterWithoutCollection {
  public static void main(String[] args) {
    String s = "I am an Indian";
    int[] i = new int[128];
    for (int j = 0; j < s.length(); j++) {
      i[(int) s.charAt(j)]++;
    }
    for (int k = (int) 'A'; k < (int) 'A' + 58; k++) {
      System.out.println((char) k + " " + i[k]);
    }
  }
}

答案 2 :(得分:0)

public class CountCharOccurrence {
    
    public static void main(String[] args) {
        String str = "Test";
        
        String temp = str.toLowerCase(); //Normalization of a string
        int[] arr = temp.chars().distinct().toArray(); //Find the distinct characters
        int chars[] = new int[256]; //An array to keep track of count of occurrences of a char
        temp.chars().map(v -> chars[v]++).toArray(); //Count the char occurrences in the array
        
        //Print the count for each distinct value
        for(int i=0; i<arr.length; i++) {
            System.out.println((char)arr[i] + " = " + chars[arr[i]]);
        }
    }

}

输出:

t = 2
e = 1
s = 1