最近没有事情做,想到刷些题做,于是看到了一道算法题:
一组随机排列的字母数组:
请编写一个时间复杂度为O(n)的算法,使得这些字母按照字母从小到大的顺序排列好。
- 字母区分大小写
- 相同字母,排序后小写排在大写前
例如:ASDSDsdcfdfdffde
结果:AcddddDDeffffsSS
之前没做过算法题,感觉一头雾水,还是记录下来,见证一下成长过程。
PS:为了防止忘记,加入了理解过程。
数组 | Value[0] | … | Value[255] |
---|---|---|---|
a[0] | “” | … | “” |
a[1] | “” | … | “” |
… | … | … | … |
a[25] | “” | … | “” |
边遍历边排序
数组 | Value[0] | Value[1] | Value[2] | … | Value[254] | Value[255] |
---|---|---|---|---|---|---|
a[0] | “a” | “” | “” | … | “” | “A” |
a[1] | “” | “” | “” | … | “” | “” |
… | … | … | … | … | … | … |
a[25] | “” | “” | “” | … | “” | “” |
小写字母从左至右写在以0开头的Value标号的位置中
大写字母从右至左侧写在以255开头的Value标号的位置中
输出时打印数组即可
代码部分
#include <iostream>
#include <stdio.h>
int main()
{
char a[255];
gets_s(a);
char result[26][255] = { "" };
int i = 0;
while(a[i]!='\0')
{
int temp ;
temp = int(a[i]) - 64 ;
if (temp >= 0 && temp < 27)
{
result[ temp - 1 ][ 255 - i ] = a[ i ];
}
else if (temp >= 33 && temp < 59)
{
result[ temp - 33 ][ i ] = a[ i ];
}
i++;
}
/* 输出部分 */
for (int r = 0; r < 26; r++)
{
for (int l = 0; l < 255; l++)
{
printf("%c",result[r][l]);
}
}
return 0;
}