问题描述:给一段字符串排序,存在一个key字符串,两个字符串中包含‘a’至‘z’的小写字母。首先按照key对input的字符串进行排序,然后对剩下的按字符大小排序。
Code:
1 #include <stdio.h>
2
3 void keysort(char *str,char *key)
4 {
5 if(str==NULL) return;
6 int hash[26]={0};
7 for(int i=0;str[i]!='\0';i++)
8 hash[str[i]-'a']++;
9 while(*key!='\0')
10 {
11 for(int j=hash[*key-'a'];j>0;j--)
12 {
13 *str=*key;
14 str++;
15 hash[*key-'a']--;
16 }
17 key++;
18 }
19 for(char ch='a';ch<='z';ch++)
20 {
21 for(int j=hash[ch-'a'];j>0;j--)
22 {
23 *str=ch;
24 str++;
25 hash[ch-'a']--;
26 }
27 }
28 }
29 int main()
30 {
31 char str[]="helloworldnicetomeetyou";
32 char key[]="low";
33 printf("%s\n",str);
34 keysort(str,key);
35 printf("%s\n",str);
36 return 0;
37 }
Output:
[root@localhost Test]# ./a.out
helloworldnicetomeetyou
llloooowcdeeeehimnrttuy