反转单词顺序
题源: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);
reverseword(s,
0,j-
1);
}
需要resize字符串的大小的原因:
因为当不改变字符串的大小的话:当输入:” hello world “时,会得到如下第二行的答案:
当使用resize改变string的大小后:
resize的用法:http://www.howsoftworks.net/cplusplus.api/std/string_resize.html
转载请注明原文地址: https://ju.6miu.com/read-662085.html