题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符顺序不变
题解分析:
两次翻转:
第一次翻转整个句子
第二次解析出每个单词并将单词翻转
void reverse(char* first, char* last) { assert(first != NULL && last != NULL); while (first < last) { char temp = *first; *first = *last; *last = temp; ++first; --last; } } void reverseTotal(char* str) { assert(str != NULL); char* first = str; char* last = str; while (*last != ‘\0‘) { ++last; } --last; reverse(first, last); first = str; last = str; // 以空格为分隔符解析单词 while (*first != ‘\0‘) { if (*first == ‘ ‘) { ++first; ++last; } else if (*last == ‘ ‘ || *last == ‘\0‘) { reverse(first, --last); ++last; first = last; } else { ++last; } } }
剑指offer (42) 单词翻转
时间: 2024-10-11 03:25:19