LeetCode(151) Reverse Words in a String

来源:互联网 发布:大恒视觉软件 编辑:程序博客网 时间:2024/06/08 17:26

题目

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.

click to show clarification.

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.

分析

给定一个字符串,以单词为单位对该字符串进行翻转,要求空间复杂度为O(1);

额外要求:

  1. 单词之间最多只能有一个空格,多余空格要删除;
  2. 字符串首尾不能添加多余空格;

方法一:此题的一个简单的解法,就是,我们可以借助vector,把字符串的单词按序加入容器,然后直接反转容器,再更新元字符串即可,但是此方法不符合空间复杂度的要求。

方法二:经过两步解决,首先,反转整个字符串,然后从前向后遍历,每经过一个单词,反转该单词一次。
当然在过程中,必须合理的处理多余空格问题。详见代码!

AC代码

class Solution {public:    void reverseWords(string &s) {        if (s.empty())            return;        //首先,反转整个字符串        reverse(s.begin(), s.end());        int n = s.size();        //再反转每个单词,同时删除多余的空格,最终的字符串头尾不能是空格,且单词之间不能有多余的空格(最多一个)        string tmp = s;        s.clear();        //标记第一个单词,方便处理单词间的空格        bool flag = true;        for (int i = 0; i < n;)        {                   //找到第一个非空格            if (tmp[i] == ' ')            {                ++i;                continue;            }//if            string::iterator beg = tmp.begin() + i, end = tmp.begin();            for (int j = i; j < n; ++j)            {                               //到达一个单词间的空格或者到整个字符串的结束                if (tmp[j] == ' ')                {                    end += j;                    reverse(beg, end);                    //链接反转后的第一个单词                    if (flag)                    {                        s = s + tmp.substr(i, j - i);                        flag = false;                    }                    else{                        s = s + " " + tmp.substr(i, j - i);                    }                    i = j + 1;                    break;                }//if                if (j == n - 1)                {                    reverse(beg, tmp.end());                    if (flag)                    {                        s = s + tmp.substr(i, j - i + 1);                    }                    else{                        s = s + " " + tmp.substr(i, j - i + 1);                    }                    i = j + 1;                    break;                }            }//for        }//for    }};

GitHub测试程序源码

0 0
原创粉丝点击