LeetCode 之 Reverse Words in a String — C 实现

Reverse Words in a String

 

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.

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.
将给定字符串按 word 翻转。

例如:

输入字符串 s = "the sky is blue",

返回 "blue is sky the".

如用 C 语言实现,则要求空间复杂度为 O(1).

说明:

word 定义为不含空格的字符序列。

输入字符串中可以首尾可以有空格,但翻转后的字符串首尾不能含空格。

输入字符串的 word 中间可能有多个空格,但翻转后的字符串 word 间只能有一个空格。

分析:

    先翻转每个 word,再翻转整个字符串,或者反过来。

翻转前先去掉字符串尾可能存在的空格,然后翻转每个 word,再翻转整个字符串,最后去掉多余的空格。

<pre name="code" class="cpp">void reverseWords(char *s) {
    char *pstart = NULL, *pend = NULL;
    char temp = 0;
    int hasword = 0;
    char *pwordstart = s;
    char *ps = s;
    
    if(!s) /*空*/
        return;
        
   while(*ps)
    {
        if(*ps != ' ') /*word*/
        {
            hasword = 1;
            pstart = ps++; /*一个word开头*/
            while(*ps && *ps != ' ')
            {
                ++ps;
            }
            pend = ps-1; /*一个word结尾*/
            for(; pstart < pend; ++pstart,--pend) /*翻转一个word*/
            {
                temp = *pstart;
                *pstart = *pend;
                *pend = temp;
            }
        }
        else
        {
            ++ps;
        }
    }
    
    if(hasword == 0)
    {
        *s = '\0';
        return;
    }
    
    while(*--ps == ' '); /*查找非空字符串结尾*/
    *++ps = '\0';
  
    for(pstart = s, pend = ps-1; pstart < pend; ++pstart,--pend)
    {
        temp = *pstart;
        *pstart = *pend;
        *pend = temp;
    }

    ps = s;
    while(*pwordstart)
    {
        if(*pwordstart == ' ' && *(pwordstart+1) == ' ') /*连着空格,不赋值*/
        {
            ++pwordstart;
        }
        else if(*pwordstart == ' ' && *(pwordstart+1) == '\0')
        {
            break;
        }
        else
        {
            *ps = *pwordstart;
            ++pwordstart;
            ++ps;
        }
    }
    *ps = '\0';
    
    return;
}

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值