题面:
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.
题解:将一个字符串里的每一个单词逆转,可单词之间却不逆转,适时想到以空串为分隔,将原字符串分隔为很多小字符串,在逐一逆转,注意指针下标的使用即可。
代码:
class Solution {
public:
string reverseWords(string s) {
int start=0;
int end=0;
int n=s.size();
while(start<n && end<n){
while(end<n && s[end]!=' '){
++end;
}
for(int i=start,j=end-1;i<j;++i,--j)
{
int temp;
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
start=++end;
}
return s;
}
};