151.Reverse Words in a String[medium]

本文介绍了一种将输入字符串中的单词逆序输出的算法。首先给出了一种简单但空间复杂度较高的方法,即将字符串分割为单词列表并逆序,再重新组合。随后提出了一种空间复杂度为O(1)的C语言实现方案,该方案通过两次逆序操作来达到目的。

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.

最基本的解决方案,非原地翻转,用python和c可以很容易解决,但空间复杂度较大,思路是先split成数组,对数组做翻转再还原


class Solution:  
    # @param s, a string  
    # @return a string  
    def reverseWords(self, s):  
        L = s.split()#字符串以单词分隔成列表  
        L.reverse()#反转列表中的单词  
        s1 = ' '.join(L)#以空格分隔列表中反转后的单词,返回字符串  
        return s1  

但是基于原地翻转空间复杂度O(1)的方法就没法用python了,使用c解决, 思路是先给每个单词词内进行翻转,然后对整个句子以字母为最小单位翻转,最后去除掉多余的空格。
void reverseWords(char *s) {
    
    int i = 0;
    int start=0;
    int end=0;
    while (s[i]){

        if (i == 0 || (s[i]!= ' ' && s[i-1]==' ') ) {
            start = i;
        }
        if (!s[i] || (s[i]!=' ' && s[i+1] == ' ') ){
            end = i;
            reverse_substring(s,start,end);

        }
        printf("i = %d, start = %d, end = %d ,%s\n",i,start,end,s);
        i++;

    }

    int last = i-1;
    reverse_substring(s,start,last);
    reverse_substring(s,0,last); 
    
        //check '   '
    i = 0;
    int lastLetter = -1;
    while (s[i]){
        if (s[i] != ' ') {
            lastLetter  = i;
        }
        i++;
    }

    s[lastLetter+1] = '\0';
}


void reverse_substring(char *s,int start,int end){
    for(int i=0;i<=(end-start)/2;i++)
    {
        char tmp = s[start+i];
        s[start+i] = s[end-i];
        s[end - i] = tmp;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值