151. Reverse Words in a String

Given an input string s, reverse the order of the words.

word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: s = "  hello world  "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Constraints:

  • 1 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?

题目:将给定字符串的单词顺序反序,但单词内部字符顺序不变。

思路:其实很简单的全部反序加每个单词单独反序即可。但题目中可能存在多个空格,要求去除这些空格,而且题目需要不增加额外的空间(C++的string data type 是 mutable的)。所以先双指针遍历一遍去除空格,然后再反序。

代码:

class Solution {
public:
    string reverseWords(string s) {
        int i = 0, j = 0, l = s.length();
        while(j < s.length()){
            if(s[j] == ' ' && (i==0 || s[i-1] == ' ')){
                j++;
            } else {
                s[i++] = s[j++];
            }
        }
        for(; i<l; i++) s.pop_back();
        while(s.length() > 0 && s.back() == ' ') s.pop_back();
        reverse(s.begin(), s.end());
        i = 0;
        while(i < s.length()){
            int pos = s.find(' ', i);
            if(pos == -1) pos = s.length();
            reverse(s.begin()+i, s.begin()+pos);
            i = pos+1;
        }
        return s;
    }
};

time: O(N), space:O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值