题解 | #字符串排序#
字符串排序
http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
这个题最开始疏忽了。也没想到测试用例这么多。总之耗时非常久。。。
最笨的思路如下:
1.获取输入数据
2.排序时将所有字母都当作小写字母或者大写字母来排序。
3.排序过程中保留其他字符的位置
这个思路看起来很简单。但在实现时,可能会有很多考虑不周全的地方。
每次排序时, 位置j和位置j+1的符号进行比较,当位置j或者位置j+1上的字符不是字母时,此时怎么办?
假设j位置不是字母,而j+1位置是字母,那么就需要找j位置的前一个字母,然后和j+1位置的字母进行比较,然后确认是否排序
总之,就是针对当前比较的j位置,j+1位置,都需要确认是不是字母,如果不是,j往前找最近的字母位,j+1往后,找最近的字母位。
然后找到的字母位进行比较,交换数据。
下一次循环时,j变为下一个字母位的index,依次循环。
这个属于c纯手撸的代码。另外需要注意冒泡排序的循环条件和单次比较的总次数。这个也很重要。不然的话,结果可能会非常意外。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_LEN 1000
#define IS_LETTER(x) ((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z'))
#define SMALL_LETTER(x) ( (x <= 'Z' && x >= 'A') ? (x+32): x)
typedef struct {
int _1st_data_index;
int _end_data_index;
} Basepos;
typedef enum {
FRONT =0,
BEHIND,
}Tflag;
void getBaseIndex(char* str, int len, Basepos* pos){
int i;
for(i=0; i < len;i++) {
if( IS_LETTER(*(str+i)) == 1){
pos->_1st_data_index = i;
break;
}
}
for(i = len -1; i >=0; i--) {
if( IS_LETTER(*(str+i)) == 1){
pos->_end_data_index = i;
break;
}
}
}
void getLetterIndex(char* str, int* index, Tflag flag){
while(IS_LETTER(str[*index]) == 0 && (str[*index] != '\0')) {
if(flag == FRONT)
(*index)--;
else
(*index)++;
}
}
int main(void) {
char str[MAX_LEN] = {0};
int i,j;
char tmp;
int tIndex[2];
int len;
Basepos pos ={-1, -1};
while(fgets(str, MAX_LEN, stdin) != NULL && str[0] != '\n') {
len = strlen(str) - 1;
getBaseIndex(str, len, &pos);
//printf("%d %d\n", pos._1st_data_index,pos._end_data_index);
if(pos._1st_data_index < 0) {
printf("%s", str);
continue;
}
//printf("1st=%c, end=%c\n", str[pos._1st_data_index],str[pos._end_data_index]);
for(i = 0; i < pos._end_data_index - pos._1st_data_index ; i++){
for(j = pos._1st_data_index; j < pos._end_data_index -i ;) {
tIndex[0] = j;
tIndex[1] = j+1;
//printf("%d %d\t", tIndex[0],tIndex[1]);
getLetterIndex(str, &tIndex[0], FRONT);
getLetterIndex(str, &tIndex[1], BEHIND);
//printf("\t%d %d\n", tIndex[0],tIndex[1]);
if(SMALL_LETTER(str[tIndex[0]]) > SMALL_LETTER(str[tIndex[1]])) {
tmp = str[tIndex[0]];
str[tIndex[0]] = str[tIndex[1]];
str[tIndex[1]] = tmp;
}
j = tIndex[1];
}
//printf("%s", str);
}
printf("%s", str);
}
return 0;
}


