Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
这道题学到的东西有string也可以用push_back函数,同时还有append函数的复习。先去除空格,然后把单个单词放在temp里面,然后再转置过来放在temp2中,然后将temp2加入ss中,同时注意每加一个单词要在单词后面补充空格,注意细节的补充完整。
代码如下:
class Solution {
public:
string reverseWords(string s) {
int i=0;
string ss;
while(i<s.size()){
string temp="\0";
if(i<s.size()&&s[i]==' ')
i++;
if(i>=s.size())break;
if(ss.size()>0){
ss+=" ";
}
for(;i<s.size()&&s[i]!=' ';i++){
temp.push_back(s[i]);
}
string temp2="\0";
for(int i=temp.size()-1;i>=0;i--){
temp2.push_back(temp[i]);
}
ss.append(temp2);
}
return ss;
}
};