题目:
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"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
思路:用空格来判断一个单词的结束和开始,用front(初始化为0) 来记录一个一个单词的开始,用i来找这个单词的结束,然后对这个单词进行反转操作;然后另front = i+1,再寻找下个单词,对这个单词进行反转操作,这样直到字符串的末尾。
代码;
class Solution {
public:
string reverseWords(string s) {
int size1 = s.size();
int front = 0;
for(int i = 0; i<=size1;i++)
{
if(i == size1 || s[i] == ' ')
{
for(int j = 0; j< (i-1 - front)/2;j++)
{
char temp = s[front+j];
s[front+j] = s[i-1-j];
s[i-1-j] = temp;
}
front = i+1;
}
}
return s;
}
};