leetcode | Reverse Words in a String

来源:互联网 发布:淘宝手链知乎 编辑:程序博客网 时间:2024/05/21 15:50

问题

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.

思路

leetcode 思路:
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.

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.

我的思路:
“hello how are you” => ""you are how hello"
要逆序输出,如果从前向后遍历,则需要把后面的单词逐个插入到已存在单词的前面(即把how插入到hello的前面),需要后移已存在字符串,冗余工作;
因此考虑从后往前遍历:
用空格分割字符串,那么第一个单词 存到缓冲区为:olleh,将其逆序,然后链接到新字符串上;当链接下一个单词之前应补上空格。(堆栈的思想)
从后向前如何判读字符串是否结束?:用字符串长度

注意:删除字符串头尾的空格

实现

C++实现

时间复杂度O(n);空间复杂度O(n)

class Solution {public:    void reverseWords(string &s) {        int length = s.size();            string ss; // new string            int i = length-1; //old string index, from tail to head            while (i >= 0) {                while (s[i] == ' ') //跳过尾部空格                    i--;                if(i < 0)                    break;                string t;                if (ss.size() != 0)                    ss.push_back(' ');//空格                while (i>= 0 && s[i] != ' ')                     t.push_back(s[i--]);                reverse(t.begin(), t.end()); //将t逆序                ss.append(t);//t附加到ss上            }            s = ss;    }};

Submission Result: Accepted

C实现

以下实现需要额外占用空间O(n)存储备份数组;
那么如何做到O(1)的空间占用? ?没想到。。。。%>_<%

//将s复制到ss中,将处理后的字符串写入到s中void reverseWords(char* s){    int length = strlen(s);    char *ss = (char*)malloc(sizeof(*ss) * (length+1));    int p = 0;    while (s[p] != '\0') //将s复制到ss中        ss[p] = s[p++];    int i = length-1; //old string index, from tail to head    int k = 0; //new string index    while (i >= 0) {        while (ss[i] == ' ')            i--;        if(i < 0)            break;        int j = 0; //temp string index        if (k != 0)            s[k++] = ' ';        char *t =  (char*)malloc(sizeof(*ss) * (length+1));//临时存储一个单词        while (i>= 0 && ss[i] != ' ')             t[j++] = ss[i--];        while (--j >= 0)            s[k++] = t[j];        free(t);    }    s[k] = '\0';    free(ss);}int main(){    char *s = (char*)malloc(sizeof(*s) * 20);    gets(s);    reverseWords2(s);    puts(s);    getchar();}

这里写图片描述

0 0
原创粉丝点击