LeetCode:Reverse Words in a String
Reverse Words in a String
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.
- 题目大意:给定一个字符串,对字符串进行逆转。
- 解题思路:看到这道题目有两种思路:
1)用两个指针从前到后扫描,分开单词,先对每个单词进行逆转,最后再对整个字符串逆转;
比如题目中给的例子:先对每个单词进行逆转得到的结果:"eht yks si eulb",然后再整体逆转即可得到"blue is sky the"。
2)根据空格切分字符串,将切分得到的单词存到vector中,然后将vector中的单词从末尾开始输出即可。
在衡量了两种方法之后,觉得第二种方法代码更加简洁方便,便选择了第二种思路。
- 实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | void reverseWords(string &s) { int i=0,j=0; int len = s.length(); vector<string> splitResult; while (i<len) { if (s[i]== ' ' ) i++; else { j=i+1; while (j<=len) { if (s[j]== ' ' ||j==len) { string tempStr = s.substr(i,j-i); splitResult.push_back(tempStr); i=j+1; break ; } else j++; } } } int size = splitResult.size(); if (size>0) { s= "" ; for (i=size-1;i>0;i--) s+=splitResult[i]+ " " ; s+=splitResult[i]; } else { s= "" ; } } |
注意的地方:我一开始提交就提示错误,要考虑到空字符串以及只有空格组成的字符串,因此要在最后作一个判断,如果splitResult为空,则直接把s赋值为""即可。
分类:
OnlineJudge
标签:
LeetCode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2013-04-29 将Sublime Text 2搭建成一个好用的IDE