题目描述

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例:

输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"

提示:

  • 在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

解答 By 海轰

提交代码

string reverseWords(string s) {
int i=0;
string res;
while(i<s.length())
{
while(s[i]==' ')
++i;
string temp="";
while(s[i]!=' '&&(i<s.length()))
{
temp+=s[i];
++i;
}
reverse(temp.begin(),temp.end());
res+=temp;
if(i<s.length()) res+=' ';
}
return res;
}

运行结果

LeetCode刷题(108)~反转字符串中的单词 III【易错】_反转字符串

解答

Demo

string reverseWords(string s) {
istringstream ss(s);
string res, str;
while(ss >> str) {
reverse(str.begin(),str.end());
res += str + " ";
}
return res.substr(0,res.length() - 1);
}

运行结果

LeetCode刷题(108)~反转字符串中的单词 III【易错】_提交代码_02


Demo(原地反转)

string reverseWords(string s) {
int n = s.size();
if(!n) return s;
int left = 0, right = 0;
while(right<n){
while(right<n && s[right]!=' ') right++; //找到下一个空格
int next = right-- + 1; //next是翻转完这个单词之后,left和right接下来要反转的单词的开始
while(left<right) swap(s[left++],s[right--]); //原地翻转
left = next; right = next; //指针跳到下一个判断位
}
return s;
}

运行结果

LeetCode刷题(108)~反转字符串中的单词 III【易错】_反转字符串_03

题目来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii