LeetCode-557. Reverse Words in a String III


問題描述
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.

題目分析

本題要求將一個(gè)句子中每個(gè)單詞的字母逆序排列,而句子中單詞的相對位置并不發(fā)生變化。其中,單詞與單詞之間使用單個(gè)空格隔開。

解題思路

單詞之間以空格隔開,因此通過空格來確定每個(gè)單詞,然后將單詞中的字母逆序排列。對于第一個(gè)單詞起始位置為零,直到查找到第一個(gè)空格i,此時(shí)i-1即為單詞的末尾,單詞長度為i,然后將該單詞逆序。下一個(gè)單詞的位置為上一個(gè)空格位置加一即i+1,找到下一個(gè)空格的位置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)                    //最后一個(gè)單詞末尾為句子長度值-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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容