leetcode[151]:Reverse Words in a String

本文介绍如何通过去除多余空格并逐个单词翻转,实现输入字符串的整体反转。详细解析了C语言中实现这一过程的方法,包括如何在原地进行操作以节省空间,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写链接内容

Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue”,
return “blue is sky the”.

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.

void reverseAWord(char *s,int begin,int end)
{
    char tmp;

    while(begin<end)
    {
        tmp=s[begin];
        s[begin]=s[end];
        s[end]=tmp;
        begin++;
        end--;
    }

}

void reverseWords(char *s) {
    int l;
    int i,j;
    for(i=0;s[i];)
    {
        if(s[i]==32)
        {
            if(s[i+1]==32 || i==0 || s[i+1]=='\0')
                for(j=i;s[j];j++) {s[j]=s[j+1];i=0;}
            else i++;
                }
        else i++;

    }
    l=strlen(s);

    for(i=0;i<l;)
    {
    if(s[i]==' ')  i++;
        j=i;
        while(s[i] && s[i]!=' ')
        {
            i++;
        }
       reverseAWord(s,j,i-1);
    }
    reverseAWord(s,0,l-1);

}

先去掉多余的空格,然后逐个单词翻转,再将整个句子翻转即可。

ABC XYZ ——>CBA ZYX——>XYZ ABC

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值