反转单词顺序
- 题源:https://leetcode.com/problems/reverse-words-in-a-string/
- leetcode 151
思路
- 先每个单词反转
- 最后整个数组反转
- 由于字符串开头和结尾和中间会有多个空格,所以需要考虑去掉多余的空格
代码
void reverseword(string &s, int start, int end){
if (start>=end) {
return;
}
else{
while (start<end) {
char temp = s[start];
s[start++] = s[end];
s[end--] = temp;
}
return;
}
}
void reverseWords(string &s) {
int i=0, j=0;
int l=0;
int len = s.length();
int wordcount = 0;
while (true) {
while (s[i]==' '&&i<len) {i++;}
if (i==len) {break;}
if (wordcount) {s[j++]=' ';} //当是第一个单词时前面不需要加空格,而后续的单词前面需要加上一个空格
l = j;
while (s[i]!=' '&&i<len) {s[j++] = s[i++];} //旋转一个单词
reverseword(s,l,j-1);
wordcount++;
}
s.resize(j); //一定需要改变string对象s的大小,原因见下面
reverseword(s,0,j-1); //整体旋转数组
}
需要resize字符串的大小的原因:
因为当不改变字符串的大小的话:当输入:” hello world “时,会得到如下第二行的答案:
当使用resize改变string的大小后:
resize的用法:http://www.howsoftworks.net/cplusplus.api/std/string_resize.html

本文介绍了解决LeetCode 151题目的方法,该题目要求反转字符串中的单词顺序。文章提供了详细的解题思路,包括先逐个单词反转再进行整体反转的方法,并附带了C++代码实现。
1188

被折叠的 条评论
为什么被折叠?



