Leetcode|Reverse Words in a String

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mike_learns_to_rock/article/details/47068599

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;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/mike_learns_to_rock/article/details/47068599