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"
void reverse(int start,int end,char *s)
{
char tmp;
while(start < end)
{
tmp = s[start] ^ s[end];
s[start] = tmp ^ s[start];
s[end] = tmp ^ s[end];
start++;
end--;
}
}
char* reverseWords(char* s)
{
int len = strlen(s);
printf("%d\n",len);
int index = 0;
for(int i = 0;i <= len;i++)
{
if(s[i] == ' '|| s[i] =='\0')
{
reverse(index,i-1,s);
index = i + 1;
}
}
return s;
}
用到的交换两个整数的技巧
tmp = a^b;
a = tmp ^a;
b = tmp ^a
另一个需要注意的地方是strlen的值与sizeof的值的关系,针对字符串,strlen(s) = sizeof(s) - 1;多的这个是'\0',一般我们的代码里都是< s.size(),这里比较特别,需要写成<= s.size(),然后再循环体重判断s[i] == 结束符这种场景。