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.

题目分析

本题要求将一个句子中每个单词的字母逆序排列,而句子中单词的相对位置并不发生变化。其中,单词与单词之间使用单个空格隔开。

解题思路

单词之间以空格隔开,因此通过空格来确定每个单词,然后将单词中的字母逆序排列。对于第一个单词起始位置为零,直到查找到第一个空格i,此时i-1即为单词的末尾,单词长度为i,然后将该单词逆序。下一个单词的位置为上一个空格位置加一即i+1,找到下一个空格的位置j,则该单词的末尾为j-1,单词长度为j-i-1然后再将该单词逆序。依次将所有单词逆序。

程序实现(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;
}

参考文献
[1] https://leetcode.com/problems/reverse-words-in-a-string-iii/#/description
[2] http://blog.csdn.net/yanqueen2011/article/details/70139408

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值