2014.3.18 03:09
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
Solution:
Reverse the whole string first, then reverse every single word. Redundant spaces must be skipped.
Total time complexity is O(n). Space complexity is O(1).
Accepted code:
1 // 1TLE, 1AC, using another char[] is unnecessary. Don't miss '++i' or '++j'. 2 class Solution { 3 public: 4 void reverseWords(string &s) { 5 int i, j; 6 int len; 7 int offset; 8 9 // remove trailing spaces 10 while (s.length() > 0 && s[s.length() - 1] == ' ') { 11 s.pop_back(); 12 } 13 len = (int)s.length(); 14 if (len == 0) { 15 return; 16 } 17 18 // remove leading spaces 19 i = 0; 20 while (i < len && s[i] == ' ') { 21 ++i; 22 } 23 s = s.substr(i, len - i); 24 len = (int)s.length(); 25 26 // reverse the whole string 27 reverse(s, 0, len - 1); 28 // reverse every word 29 i = 0; 30 while (i < len) { 31 j = i; 32 while (j < len && s[j] != ' ') { 33 ++j; 34 } 35 reverse(s, i, j - 1); 36 i = j; 37 while (i < len && s[i] == ' ') { 38 ++i; 39 } 40 } 41 42 // remove redundant spaces between words 43 offset = 0; 44 i = 0; 45 while (true) { 46 j = i; 47 while (j < len && s[j] != ' ') { 48 s[j - offset] = s[j]; 49 ++j; 50 } 51 i = j; 52 if (i == len) { 53 break; 54 } 55 s[i - offset] = s[i]; 56 ++i; 57 while (i < len && s[i] == ' ') { 58 ++i; 59 ++offset; 60 } 61 } 62 63 while (offset > 0) { 64 s.pop_back(); 65 --offset; 66 } 67 } 68 private: 69 void reverse(string &s, int ll, int rr) { 70 int i; 71 char ch; 72 73 for (i = ll; i < ll + rr - i; ++i) { 74 ch = s[i]; 75 s[i] = s[ll + rr - i]; 76 s[ll + rr - i] = ch; 77 } 78 } 79 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)