2 回答

TA貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用流的高效方法
Map<Character, Long> freq = Arrays.stream(arr). collect(Collectors.groupingBy(Character::charValue, Collectors.counting()));

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
一種直接的方法是使用2個(gè)數(shù)組,一個(gè)用于存儲(chǔ)字符串中出現(xiàn)的字符,區(qū)分大小寫,另一個(gè)用于存儲(chǔ)其相應(yīng)的頻率。
兩個(gè)數(shù)組都使用字符串長度的大小進(jìn)行聲明,以下示例代碼展示了如何僅使用數(shù)組和簡單的邏輯來實(shí)現(xiàn)您想要的效果。
示例代碼
String str = "The array must be in alphabetical order and also store non-alphabetical characters (including spaces)";
char[] charArr = new char[str.length()];
int[] freqArr = new int[str.length()];
int idx = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
boolean isFound = false;
for (idx = 0; idx < str.length(); idx++) {
if (freqArr[idx] == 0) {
break;
}
if (c == charArr[idx]) {
freqArr[idx]++;
isFound = true;
break;
}
}
if (!isFound) {
charArr[idx] = c;
freqArr[idx]++;
}
}
//Sort charArr and freqArr arrays
char tempChar;
int tempFreq;
for (int i = 1; i < str.length(); i++) {
for (int j = i; j > 0; j--) {
if (charArr[j] < charArr [j - 1]) {
tempChar = charArr[j];
charArr[j] = charArr[j - 1];
charArr[j - 1] = tempChar;
tempFreq = freqArr[j];
freqArr[j] = freqArr[j - 1];
freqArr[j - 1] = tempFreq;
}
}
}
打印字母頻率
for (int i = 0; i < str.length(); i++) {
if (freqArr[i] != 0) {
System.out.printf("%s:%d", charArr[i], freqArr[i]);
System.out.println();
}
}
控制臺輸出
[:13],[(:1],[):1],[-:1],[T:1],[a:13],[b:3],[c:6],[d: 3],[e:8],...
添加回答
舉報(bào)