题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
#include <stdio.h> #include <string.h> #define MAX 10001 void delete_char(char *s, int i) { if (s == NULL || i < 0 || i >= strlen(s)) { return; } int len = strlen(s); for (int j = i; j < len - 1; j++) { s[j] = s[j+1]; } s[len-1] = '\0'; } void reverse_s(char *start, char *end){ char m; for(int i = 0; start + i < end - i; i++){ m = *(end - i); *(end - i) = *(start + i); *(start + i) = m; } } int main(){ char arr[MAX]; /* scanf("%s", arr); int len = strlen(arr) - 1; */ fgets(arr, sizeof(arr), stdin); arr[strlen(arr) - 1] = '\0'; int len = strlen(arr); for(int i = 0; i < len; i++){ if((arr[i] >= 'a') && (arr[i] <= 'z')){} else if((arr[i] >= 'A') && (arr[i] <= 'Z')){} else{ if(arr[i - 1] == ' ') delete_char(arr, i); else arr[i] = ' '; } } len = strlen(arr); char *start = arr; for(int i = 0; i <= len; i++){ if((arr[i] == ' ') || (arr[i] == '\0')){ reverse_s(start, arr + i - 1); start = arr + i + 1; } } reverse_s(arr, arr + len - 1); printf("%s", arr); return 0; }