【LeetCode】151. 翻转字符串里的单词

题目

给定一个字符串,逐个翻转字符串中的每个单词。

示例 1:

输入: "the sky is blue"
输出: "blue is sky the"

示例 2:

输入: "  hello world!  "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

示例 3:

输入: "a good   example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

说明:

  • 无空格字符构成一个单词。
  • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

进阶:请选用 C 语言的用户尝试使用 O(1) 额外空间复杂度的原地解法。

本题同【剑指Offer】面试题58 - I. 翻转单词顺序

思路一:栈

通过空格分割单词并放入栈中,然后依次从栈中取出。

代码

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

class Solution {
public:
    string reverseWords(string s) {
        istringstream is(s);
        stack<string> st;
        string str, res;
        while (is >> str) {
            st.push(str);            
        }
        while (!st.empty()) {
            if (!res.empty()) {
                res += " ";
            }
            res += st.top();
            st.pop();
        }
        return res;
    }
};

另一种写法

将字符串放入vector中,然后从后向前遍历。

class Solution {
public:
    string reverseWords(string s) {
        string res, str;        
        istringstream is(s);
        vector<string> svec;
        while (is >> str) {
            svec.push_back(str);
        }
        for (int i = svec.size() - 1; i >= 0; --i) {
            if (!res.empty()) res += ' ';
            res += svec[i];
        }
        return res;
    }
};

思路二:reverse

从前向后,先对每个单词反转,再对整个句子反转。

代码

时间复杂度:O(n)
空间复杂度:O(1)

class Solution {
public:
    string reverseWords(string s) {
        string res;
        for (int i = 0; i < s.size(); ++i) {
            string tmp;
            while (i < s.size() && s[i] == ' ') ++i;
            while (i < s.size() && s[i] != ' ') {
                tmp += s[i];
                ++i;
            }
            if (!tmp.empty()) {
                reverse(tmp.begin(), tmp.end()); //对单词反转
                if (!res.empty()) res += ' ';
                res += tmp;
            }            
        }
        reverse(res.begin(), res.end());//对整个句子反转
        return res;
    }
};
原文地址:https://www.cnblogs.com/galaxy-hao/p/12507229.html