LeetCode 151 反转字符串中的单词
🟡 中等 https://leetcode.cn/problems/reverse-words-in-a-string/description/
先分割再拼接
class Solution {
public:
string reverseWords(string s) {
vector<string> res;
int n = s.size();
int start = 0;
int end = n-1;
while(s[start]==' ')start++;
while(s[end]==' ') end--;
s = s.substr(start,end-start+1);
s = ' '+s;
n = s.size();
int i = n-1,j = n-1;
while(i>=0){
if(s[i]!=' '&&s[i+1]==' ') j = i;
if(s[i]!=' '&&s[i-1]==' ') res.push_back(s.substr(i,j-i+1));
i--;
}
string res_s = res[0];
for(int i = 1;i<res.size();i++){
res_s+=' ';
res_s+=res[i];
}
return res_s;
}
};
常数空间
官解
class Solution {
public:
string reverseWords(string s) {
int n = s.size();
int start = 0;
int index = 0;
reverse(s.begin(),s.end());
while(start<n){
if(s[start]!=' '){
int end = start;
while(start<n&&s[start]!=' ') s[index++] = s[start++];
reverse(s.begin()+index-1-(start-1-end+1)+1,s.begin()+index-1+1);
//reverse 函数 第二个下标要+1,因为end() 是n-1的后一个;
s[index++] = ' '; //到最后 index指向下一次写入的位置,index-1是空格,index-2是最后一个字母。
}
start++;
}
s.erase(s.begin()+index-1,s.end());
return s;
}
};