Java一串由数字组成的字符串,求各个数字出现的次数,并按出现次数的大小从小到大排序,若出现的次数相同
。例如:
String s = "10771034948754277771578";
最后输出结果应该是
6:0次
3:1次
9:1次
2:1次
0:2次
5:2次
8:2次
4:3次
1:3次
7:8次
求代码 展开
class A {
public static void bubbleSort(int[] n, int[] idx) {
int t, j;
for (int i=0;i<n.length-1;i++) {
for (j=0;j<n.length-1-i;j++) {
if (n[j]>n[j+1]) {
t = n[j];n[j] = n[j+1];n[j+1] = t;
t = idx[j]; idx[j] = idx[j+1]; idx[j+1] = t;
}
}
}
}
public static void main(String argv[]) {
String s = "10771034948754277771578";
int n[] = {0,0,0,0,0,0,0,0,0,0};
int idx[] = {0,1,2,3,4,5,6,7,8,9};
for (int i=0;i<s.length();i++) {
n[s.charAt(i)-'0'] ++;
}
bubbleSort(n, idx);
for (int i=0;i<n.length;i++) {
System.out.printf("%d: %d次\n",idx[i], n[i]);
} }}
谢谢大哥,不过如果出现的次数相同,要把后出现的数字排在后面,这点没做到啊
哦,没注意这要求。
public class A {
public static void bubbleSort(int[] n, int[] idx) {
int t, j;
for (int i=0;i<n.length-1;i++) {
for (j=0;j<n.length-1-i;j++) {
if (n[j]>n[j+1]) {
t = n[j];n[j] = n[j+1];n[j+1] = t;
t = idx[j]; idx[j] = idx[j+1]; idx[j+1] = t;
}
}
}
}
public static void main(String argv[]) {
String s = "10771034948754277771578";
int n[] = {0,0,0,0,0,0,0,0,0,0};
int idx[] = {0,0,0,0,0,0,0,0,0,0};
int k= 0;
boolean f;
for (int i=0;i<s.length();i++) {
f = false;
int ch = s.charAt(i)-'0';
for (int j=0;j<k;j++) {
if (idx[j] == ch) {
n[j]++;
f = true;
}
}
if (!f) {
idx[k] = ch;
n[k++] = 1;
}
}
bubbleSort(n, idx);
for (int i=0;i<n.length;i++) {
System.out.printf("%d: %d次\n",idx[i], n[i]);
}
}
}
按你的要求,你给出的结果也是错的,8出现在5前面.