刷题日期2026.4.29题目151. 反转字符串中的单词难度中等语言C 语言参考文章https://blog.csdn.net/weifeng425/article/details/132200146参考视频https://www.bilibili.com/video/BV1uT41177fX一、看到题目的第一想法题目要求反转单词顺序去掉前导、后缀、中间多余空格单词之间只保留一个空格第一反应不能开新字符串 →原地修改先整体反转再把每个单词反转回来双指针清理空格这是字符串最经典的面试题二、解题思路三步法整体反转字符串逐个反转每个单词双指针清理多余空格最终效果单词顺序颠倒 空格规范。三、AC 代码C 语言c运行#include stdio.h #include string.h #include ctype.h // 反转区间 void reverse(char* s, int start, int end) { while (start end) { char temp s[start]; s[start] s[end]; s[end] temp; start; end--; } } char* reverseWords(char* s) { int len strlen(s); // 1. 整体反转 reverse(s, 0, len - 1); // 2. 反转每个单词 去空格 int index 0; for (int i 0; i len; i) { if (s[i] ) continue; int start i; while (i len s[i] ! ) i; int end i - 1; reverse(s, start, end); // 复制单词到前面 for (int j start; j end; j) { s[index] s[j]; } // 单词间加空格 if (index len) s[index] ; } // 去掉末尾空格 if (index 0 s[index - 1] ) index--; s[index] \0; return s; }四、实现过程中遇到的困难空格太多难处理前导、后缀、中间多空格。✅ 解决双指针直接覆盖自动去重。单词反转逻辑混乱✅ 解决先整体反转再局部反转。最后多一个空格✅ 解决结束前手动去掉。五、今日收获心得字符串单词反转 整体反转 局部反转这是通用模板原地处理字符串 双指针不用额外数组空间 O (1)。面试超级高频题字节、阿里、腾讯都爱考。字符串体系彻底掌握整体反转 → 左右双指针分段反转 → 循环 反转单词反转 → 整体 局部反转去空格 → 双指针覆盖六、总结LeetCode 151 是字符串原地修改的天花板题目。记住核心整体反转 → 单词反转 → 清理空格直接秒杀坚持每日一题算法稳步提升