[LeetCode] Reverse Words in a String II
Problem Description:
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Could you do it in-place without allocating extra space?
Since this problem has guaranteed that the string does not contain all the leading and trailing spaces and all words are separated by a single space, it will be much easier to be solved in space. The idea is to reverse the whole string first. Then we visit the string from left to right, each time we meet a space, we reverse the immediate word before it.
The code is as follows.
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 reverse(s.begin(), s.end()); 5 s += ' '; 6 int i = 0, j = 0, n = s.length(); 7 while (i < n && j < n) { 8 while (j < n && s[j] != ' ') j++; 9 if (j < n) { 10 reverseBetween(s, i, j - 1); 11 i = j + 1; 12 j = i; 13 } 14 } 15 s.resize(n - 1); 16 } 17 private: 18 void reverseBetween(string &s, int i, int j) { 19 while (i < j) 20 swap(s[i++], s[j--]); 21 } 22 };
Note that we append a space to the reversed string to facilitate the detection of the last word.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档