链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc"
注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
思路:先用一个临时的字符串变量存储,遇到空格或者末尾时,用reverse()函数翻转该字符串变量,再将其加入总的字符串中,注意空格和结束符也要加入到字符串中。
class Solution {
public:
string reverseWords(string s) {
string a = "";
string temp = "";
int len = s.length();
for(int i = 0; i <= len; i++)
{
if(s[i] == ' ' || s[i] == '\0')
{
reverse(temp.begin(), temp.end());
a = a + temp;
a = a + s[i];
temp = "";
}
else
temp += s[i];
}
return a;
}
};
来源:CSDN
作者:tmhhh
链接:https://blog.csdn.net/weixin_43569916/article/details/103581445