题解 | #HJ102 字符统计#
字符统计
http://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
C语言版本
#include <stdio.h>
#include <string.h>
int main() {
char string[1001];
scanf("%s", string);
int length = strlen(string);
int hist_c[36] = {0};
for (int i = 0; i < length; i++) {
if (('0' <= string[i]) && (string[i] <= '9')) {
hist_c[string[i]-'0'] += 1;
} else if (('a' <= string[i]) && (string[i] <= 'z')) {
hist_c[10 + string[i]-'a'] += 1;
}
}
int count = 0;
for (int i = 0; i < 36; i ++) {
if (hist_c[i]>0) {
count += 1;
}
}
char c[37] = "0123456789abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 36; i++) {
for (int j = i+1; j < 36; j++) {
if ((hist_c[i] < hist_c[j]) || ((hist_c[i] == hist_c[j]) && (c[i] > c[j]))) {
int ti;
char tc;
ti = hist_c[i];
hist_c[i] = hist_c[j];
hist_c[j] = ti;
tc = c[i];
c[i] = c[j];
c[j] = tc;
}
}
}
c[count] = '\0';
printf("%s\n", c);
return 0;
}
Python版本
while True:
try:
string = input()
c_set = set([c for c in string])
c_hist = [(c, string.count(c)) for c in c_set]
c_hist.sort(key=lambda x: (-x[1], x[0]))
out = ''.join([x[0] for x in c_hist])
print(out)
except Exception:
break
这时候不得不感慨,“人生苦短,我用 Python”。