题目描述
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.
题目解读
- 输入一英文,将这个英文句子中的每个单词进行翻转
解题思路
- 考虑空格,依次将单词进行翻转
- 注意:其中有一些数学运算需要仔细把握
Code
# include<stdio.h>
# include<string.h>
char* reverseWords(char* s)
{
int i, j;
int index1 = 0, index2;
int len;
char temp;
len = strlen(s);
for (i = 0; i < len; i ++)
{
if(s[i] == ' ')
{
index2 = i - 1;
for (j = 0; j < ((index2 - index1) + 1) / 2; j ++)
{
temp = s[index1 + j];
s[index1 + j] = s[index1 + ((index2 - index1) + 1) - j - 1];
s[index1 + ((index2 - index1) + 1) - j - 1] = temp;
}
index1 = i + 1;
}
else if(i == len - 1)
{
index2 = len - 1;
for (j = 0; j < ((index2 - index1) + 1) / 2; j ++)
{
temp = s[index1 + j];
s[index1 + j] = s[index1 + ((index2 - index1) + 1) - j - 1];
s[index1 + ((index2 - index1) + 1) - j - 1] = temp;
}
}
}
return s;
}
int main()
{
char s[100] = {"Let's take LeetCode contest"};
char *temp;
temp = reverseWords(s);
printf("%s\n", temp);
}
思考
- 结果差强人意...