码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode | Reverse Words in a String

时间:2015-05-05 12:41:25      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:reverse

问题

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++实现

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)

//将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();
}

技术分享

leetcode | Reverse Words in a String

标签:reverse

原文地址:http://blog.csdn.net/quzhongxin/article/details/45499751

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!