String - count the frequency of characters in a string Given a string S, count the frequency of characters in the string S (the occurrences of a character present in the string) Input: hello world where: First-line represents the input string Output: d 1 e 1 h 1 l 3 o 2 r 1 w 1 Explanation: Print the count of each distinct letter present in string S. Assumptions: String contains only lower case letters Length of string S can be 0 to 10000
时间: 2023-11-27 09:50:42 浏览: 66
Basic4Android 啟動手冊
4星 · 用户满意度95%
Here's a possible solution to count the frequency of characters in a string:
```
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
Map<Character, Integer> freq = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
```
The code reads a string from the standard input, and then iterates over the characters of the string, updating a map that stores the frequency of each character. The `getOrDefault` method is used to initialize a count of zero for each character that is encountered for the first time. Finally, the code prints the count of each distinct letter present in the string.
阅读全文