栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

151. Reverse Words in a String

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

151. Reverse Words in a String

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

A 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 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)

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1010560.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号