给定一个字符串s,s包含以空格分隔的若干个单词,请对s进行如下处理后输出
1、单词内部调整:对每个单词字母重新按字典序排序
2、单词间顺序调整:
1)统计每个单词出现的次数,并按次数降序排列;
2)次数相同时,按单词长度升序排列;
3)次数和单词长度均相同时,按字典序升序排列。
请输出处理后的字符串,每个单词以一个空格分隔。
输入描述
-行字符串,每个字符取值范围:[a-zA-20-9]以及空格,字符串长度范围:[1,1000]
输出描述
重新排序后的字符串,每个单词间隔1个空格,且首尾无空格
#include <string.h>
#include <stdio.h>
struct stu_str{
char str_raw[100];
char str_orded[100];
int length;
int times;
};
void order_str(char * p) {
int n = strlen(p);
for(int i = 1;i<n;i++){
for(int j = 0;j<n-i;j++){
if(p[j]>p[j+1]){
char t = p[j];
p[j] = p[j+1];
p[j+1] = t;
}
}
}
}
void put_in_words(struct stu_str words[],int * pCnt,char * str,char *raw_str){
int i = 0;
for(i = 0;i<*pCnt;i++){
if(strcmp(words[i].str_orded,str) == 0){ //发现已经出现过,那么次数增加1,其它不变。
words[i].times++;
break;
}
}
if(i == *pCnt){
strcpy(words[(*pCnt)].str_raw,raw_str);//当word里面还没有新读入的串,增加一项
strcpy(words[(*pCnt)].str_orded,str);//拷贝排序后的。
words[*pCnt].length = strlen(str);//得到长度
words[*pCnt].times = 1;//新的肯定是第一次出现。
(*pCnt)++;
}
}
void read_all_words1(struct stu_str words[],int *pCnt){
char str[1000000] = {0};
char * p = str;
gets(str);
while(p = strtok(p," ")){
char temp[1000] = {0};
strcpy(temp,p);
order_str(p);
put_in_words(words,pCnt,p,temp);
p = NULL;
}
}
void myorder(struct stu_str words[],int cnt) {
for(int i = 1;i<cnt;i++){
for(int j = 0;j< cnt-i;j++){
if(words[j].times < words[j+1].times||
(words[j].times == words[j+1].times&& words[j].length > words[j+1].length)||
(words[j].times == words[j+1].times&& words[j].length == words[j+1].length &&
strcmp(words[j].str_orded , words[j+1].str_orded) == 1)){
struct stu_str t = {0};
t = words[j];
words[j] = words[j+1];
words[j+1] = t;
}
}
}
}
int main() {
struct stu_str words[100] = {0};
int cnt = 0;
read_all_words1(words, &cnt);
myorder(words, cnt);
for (int i = 0; i < cnt; i++) {
for (int j = 0; j < words[i].times; j++) {
printf("%s ", words[i].str_orded);
}
}
}