[Problem]
给出一个英语句子,希望你把句子里的单词顺序都翻转过来
[Analysis]
为保证额外的空间开销,在原字符串上处理:首先将整个句子翻转一遍,然后从头到尾遍历一次,翻转每一个单词。
[Solution]
#include <stdio.h> #include <string.h> #define MAX_LEN 10001int main(){ // input datachar str[MAX_LEN];gets(str);int len = strlen(str);// reverse all charactersfor(int i = 0; i < len/2; ++i){ char tmp = str[i];str[i] = str[len-1-i];str[len-1-i] = tmp;}// reverse wordsint start = 0, end = 0;while(end < len){ // filter blankswhile(end < len && str[end] != ' '){ end++;}// reverseif(end > start){ for(int i = 0; i < (end-start)/2; ++i){ char tmp = str[start + i];str[start + i] = str[end-1-i];str[end-1-i] = tmp;}start = end;}// move forwardstart++;while(start < len && str[start] == ' '){ start++;}end = start;}// output resultprintf("%s\n", str);return 0; }