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?

复制代码
class Solution {
public:
    void reverse(string &s,int start,int end){
        for(int i=start,j=end-1;i<j;i++,j--){
            swap(s[i],s[j]);
        }
    }
    void removeExtraSpace(string &s){
        int slow=0;
        for(int fast=0;fast<s.size();fast++){
            if(s[fast]!=' '){
                if(slow!=0)s[slow++]=' ';
                while(fast<s.size() && s[fast]!=' ')s[slow++]=s[fast++];
            }
        }
        s.resize(slow);
    }
    string reverseWords(string s) {
        removeExtraSpace(s);
        reverse(s,0,s.size());
        int start=0;
        for(int i=0;i<=s.size();i++){
            if(i==s.size() || s[i]==' '){
                reverse(s,start,i);
                start=i+1;
            }
        }
        return s;
    }
};

注意:

1.需要删除多余空格,但是每个单词之间又需要一个空格

2.总体思路:先把多余空格删除,再把整个字符串反转,再依次把每一个单词反转

3.reverse函数很简单,不过多赘述

4.removeExtraSpace函数:使用快慢指针,重点是当fast所在位置不为空格且slow>0就需要手动添加一个空格。

相关推荐
总要学点什么33 分钟前
第105篇:三维特效-流动图片墙体效果——让箭头沿墙长滚,它俩竟是同一份代码
开发语言·javascript·ecmascript·gis·webgl·材质·cesium
xiaoye-duck1 小时前
《C++ 项目:手写大模型接入 SDK》会话模块整合:内存 SessionManager 与 DataManager 持久化联动
开发语言·数据库·c++·语言模型
Funlang2 小时前
龙芯上的 Fun:从跑起来到机器码
开发语言·龙芯
总要学点什么2 小时前
第104篇:三维特效-流动墙体效果——让贴图沿墙流动,它却只肯走一条对角线
开发语言·javascript·ecmascript·gis·webgl·材质·cesium
旖旎夜光3 小时前
【C++ 基础入门】C++11 新特性(中):右值引用、移动语义与完美转发
开发语言·c++·笔记·学习
ShineWinsu3 小时前
对于Qt:QTabWidget常见属性的解析
开发语言·数据库·c++·qt·浏览器·qtabwidget·标签页
普通人64 小时前
WebGL与WebGPU入门指南
开发语言·webgl·1024程序员节
꧁细听勿语情꧂4 小时前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
SomeOtherTime4 小时前
Rust集合(AI回答)
开发语言·后端·rust
曦樂~4 小时前
【Web Development】03JavaScript 基础和事件
开发语言·前端·javascript