問題描述
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.
題目分析
本題要求將一個句子中每個單詞的字母逆序排列,而句子中單詞的相對位置并不發(fā)生變化。其中当叭,單詞與單詞之間使用單個空格隔開桑驱。
解題思路
單詞之間以空格隔開鳖粟,因此通過空格來確定每個單詞缕贡,然后將單詞中的字母逆序排列曙强。對于第一個單詞起始位置為零福稳,直到查找到第一個空格i涎拉,此時i-1即為單詞的末尾,單詞長度為i,然后將該單詞逆序鼓拧。下一個單詞的位置為上一個空格位置加一即i+1半火,找到下一個空格的位置j,則該單詞的末尾為j-1季俩,單詞長度為j-i-1然后再將該單詞逆序钮糖。依次將所有單詞逆序。
程序?qū)崿F(xiàn)(C語言)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* reverseWords(char* s)
{
int start=0,end=0,j=0,i=0;
int strl=strlen(s) ;
char *result;
result = (char* )malloc(sizeof(char)*(strl+1));
printf("%d\n",strlen(s));
printf("%c\n",*(s+strlen(s)));
for (i=0;i<=strl;i++)
{
if (s[i]==32 || i==strl) //最后一個單詞末尾為句子長度值-1
{
end=i-1;
for (j=start;j<=end;j++)
{
result[j]=s[end-j+start]; //單詞逆序
printf("%c\n",result[j]);
}
result[i]=' '; //單詞之間空格
start=i+1;
printf("%c\n",result[i]);
}
}
result[strl]='\0';
return result;
}
int main()
{
char *strs="Let's take LeetCode contest";
char *restrs;
char *result;
result=reverseWords(strs);
printf("%s",result);
return 0;
}
參考文獻(xiàn)
[1] https://leetcode.com/problems/reverse-words-in-a-string-iii/#/description
[2] http://blog.csdn.net/yanqueen2011/article/details/70139408