Leetcode|Reverse Words in a String

本文详细介绍了三种改进的字符串单词反转算法,包括两遍扫描、单遍扫描和原地操作方法,重点阐述了如何在不分配额外空间的情况下实现字符串反转,并提供了解决方案的代码示例。

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

Given s = “the sky is blue”,
* return “blue is sky the”.
这种问题一般有三种解法:
1,One simple approach is a two-pass solution: First pass to split the string by spaces into an array of words, then second pass to extract the words in reversed order.
这种方法需要额外空间存储单词,而且需要遍历两边。
2,We can do better in one-pass. While iterating the string in reverse order, we keep track of a word’s begin and end position. When we are at the beginning of a word, we append it.
需要额外空间,从后面遍历,只需要遍历一次。(当然如果用C,需要先遍历一次获取尾部)
3,in-place 方法:需要O(1)的额外空间,多次翻转的方法;(如果单词之间以前开头和结尾处有很多空格,处理会麻烦一些,很考验人)

Reverse Words in a String .II
* Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
*
* The input string does not contain leading or trailing spaces and the words are always separated by a single space.
*
* For example,
* Given s = “the sky is blue”,
* return “blue is sky the”.
*
* Could you do it in-place without allocating extra space?
如果不考虑空格问题,非常容易利用多次反转解决。
//先定义reverse函数,翻转字符串

void reverse(char *s,int start, int last){
    while(start<last){
        char temp=s[start];
        s[start++]=s[last];
        s[last--]=temp;
    }
}
void reverseWords_no_space(char *s){
  int j;//len
  for(j=0;s[j]!='\0';j++);//找到尾部
  reverse(s,0,j-1);
  for(int begin=0,i=0;i<=j;i++){
    if(s[i]==' '||s[i]=='\0'){
        reverse(s,begin,i-1);
        begin=i+1;
    }
  }

}

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.

void reverse(char *s,int start, int last){
    while(start<last){
        char temp=s[start];
        s[start++]=s[last];
        s[last--]=temp;
    }
}
void reverseWords(char *s) {//只有一个单词,就把两边的空格去掉
    int index=0;//先用于记录长度
    //i为不为空格的第一位
    for(index=0;s[index]!='\0';index++);//找到尾部
    reverse(s,0,index-1);
    for(int i=0,begin=0;i<=index;i++){//反转单词
        if(s[i]==' '||s[i]=='\0') continue;
        else {
            begin=i;
            for(;s[i]!=' '&&s[i]!='\0';i++);
            reverse(s,begin,i-1);
            begin=i+1;
         }
    }
    for(int i=0,newi=0,extraspace=true;i<=index;i++){
        if(s[i]!=' '||(s[i]==' '&&!extraspace)){//保证单词之间以及开头处不会有多余的空格
            if(s[i]!='\0') s[newi++]=s[i];
            else {
                if(newi>0&&s[newi-1]==' ') s[--newi]='\0';//处理结尾的空格
                else s[newi]='\0';
                return;
            }
            if(s[i]==' ') extraspace=true;
            else extraspace=false;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值