题目链接:
https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
难度:简单
557. 反转字符串中的单词 III
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例:
输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"
提示:
在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
简单题。。。。
建立新串
class Solution {
public:
string reverseWords(string s) {
string ans="";
int n=s.size();
int i=0;
while(i<n){
int start=i;
while(i<n&&s[i]!=' '){
i++;
}
for(int k=start;k<i;k++){
ans.push_back(s[i+start-1-k]);
}
while(i<n&&s[i]==' '){
ans.push_back(' ');
i++;
}
}
return ans;
}
};
原地修改
class Solution {
public:
string reverseWords(string s) {
int n=s.size();
int i=0;
while(i<n){
int start=i;
while(i<n&&s[i]!=' '){
i++;
}
int end=i-1;
while(start<end){
swap(s[start], s[end]);
start++;
end--;
}
while(s[i]==' '&&i<n){
i++;
}
}
return s;
}
};