我有一段代碼會告訴我字符串中出現次數最多的字符。該cade如下:靜態字符串中字符數的計數
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MaximumOccurringChar {
static final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today. Help!";
public static void main(String[] args) {
MaximumOccurringChar test = new MaximumOccurringChar();
List<Character> result = test.maximumOccurringChars(TEST_CASE_1, true);
System.out.println(result);
}
public List<Character> maximumOccurringChars(String str) {
return maximumOccurringChars(str, false);
}
// set skipSpaces true if you want to skip spaces
public List<Character> maximumOccurringChars(String str, Boolean skipSpaces) {
Map<Character, Integer> map = new HashMap<>();
List<Character> occurrences = new ArrayList<>();
int maxOccurring = 0;
// creates map of all characters
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (skipSpaces && ch == ' ') // skips spaces if needed
continue;
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
if (map.get(ch) > maxOccurring) {
maxOccurring = map.get(ch); // saves max occurring
}
}
// finds all characters with maxOccurring and adds it to occurrences List
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == maxOccurring) {
occurrences.add(entry.getKey());
}
}
return occurrences;
}
}
但我無法弄清楚如何顯示他們的計數。例如,如果我放入「aasssddeefgt」,它說s發生次數最多,但它並不告訴我它發生了3次。誰能幫忙?
你在你的'map'計數。需要從那裏帶走它們。爲什麼不只是返回另一個Map而不是List呢? – Thilo 2014-09-02 01:35:46
刪除'List occurrences'並使用您的代碼,以便它不使用發生,只需使用地圖。你想要的值是在地圖 –
2014-09-02 01:37:00
你可以請幫助通過修改代碼? – 2014-09-02 01:48:49