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.
题目大意:给出一个字符串,对其中的每个单词执行逆转操作。
代码如下:
void swap(char* a, char* b)
{
char temp = *a;
*a = *b;
*b = temp;
}
void reverse(char* s, int len)
{
for(int i = 0;i < len/2;i++)
swap(s+i, s+len-i-1);
}
char* reverseWords(char* s) {
int len = strlen(s);
for(int i = 0, j = 0;i <= len;i++){
if(*(s+i) == ' ' || *(s+i) == '\0'){
reverse(s+j, i-j);
j = i+1;
}
}
return s;
}