Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
算法
空间:O(n)
时间:O(n)
1、中间有多个空格的处理
2、没有空格的字符串
3、反转后开头和结尾不能有空格
4、最后的结果单词间得有空格
所以,由以上我们有两种思路,一种就是以单词为单位反转,这个需要用到vector,reverse即可,需要两次for循环,如下:
class Solution {
public:
void reverseWords(string &s) {
vector<string> des;
if(s.empty())
return;
int len = s.size();
for(int i = 0; i < len; i++){
if(s[i] == ' ')
continue;
string word;
while(i < len && s[i] != ' '){
word += s[i];
i++;
}
des.push_back(word);
}
reverse(des.begin(), des.end());
if(des.empty())
s = "";
else {
s.clear();
int j ;
for(j = 0; j < des.size() -1; j++){
s += des[j];
s += ' ';
}
s += des[j];
}
}
};
算法
栈
class Solution {
public:
void reverseWords(string &s) {
stack<string> des;
if(s.empty())
return;
int len = s.size();
for(int i = 0; i < len; i++){
if(s[i] == ' ')
continue;
string word;
while(i < len && s[i] != ' '){
word += s[i];
i++;
}
des.push(word);
}
if(des.empty())
s = "";
else {
s.clear();
int j ;
int length = des.size();
for(j = 0; j < length -1; j++){
s += des.top();
des.pop();
s += ' ';
}
s += des.top();
}
}
};
算法
c语言版本
空间:O(1)
时间:O(n)
//反转每个单词,最后再反转整个句子
#include <stdio.h>
#include <string.h>
void reverse_sub(char *s, int len) {
char tmp;
int i;
for (i = 0; i < len / 2; ++i) {
tmp = s[i];
s[i] = s[len - i - 1];
s[len - i - 1] = tmp;
}
}
void reverseWords(char *s) {
int i = 0;
int cur = 0; // current pos of dealed string
int cnt = 0; // current words' length
int word_cnt = 0;
while (1) {
// skip spaces
while (s[i] == ' ')
++i;
if (s[i] == '\0')
break;
if (word_cnt++)
s[cur++] = ' ';
// count the length and move
cnt = 0;
while (s[i + cnt] != '\0' && s[i + cnt] != ' ') {
if (cur != i)
s[cur + cnt] = s[i + cnt];
cnt++;
}
reverse_sub(s + cur, cnt);
// update the pos and add space
i += cnt;
cur += cnt;
}
s[cur] = '\0';
reverse_sub(s, cur);
}
int main() {
char str[100];
while (gets(str)) {
printf("'%s'\n", str);
reverseWords(str);
printf("'%s'\n\n", str);
}
return 0;
}
这里写代码片