字符串中的单词逆转,如将“Today is Friday!”,逆转为“Friday! is Today”;
算法思路,先逆转各单词,“Today is Friday!”逆转为 “yadoT si !yadirF”,再将整个字符串逆转,“Friday! is Today”
代码实现
void reverse(char* str, int begin, int end) { if(begin + 1 < end) { char temp; int i = begin,j = end - 1; while(i < j) { temp = str[i]; str[i] = str[j]; str[j] = temp; ++i; --j; } } } void foo(char* str, int begin, int end) { int i,j = begin; for(j = begin; j < end; ++j) { while(' ' == str[j]) { ++j; } i = j++; while(j < end && ' ' != str[j]) { ++j; } if(i+1 < j) { reverse(str,i,j); } } reverse(str,begin,end); }