LeetCode75——Day6

文章目录

一、题目

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?

二、题解

cpp 复制代码
class Solution {
public:
    string reverseWords(string s) {
        vector<string> tmp;
        istringstream ss(s);
        string token;
        while(getline(ss,token,' ')) tmp.push_back(token);
        string res = "";
        int n = tmp.size();
        for(int i = n - 1;i >= 0;i--){
            if(tmp[i] != ""){
                res += tmp[i];
                res += " ";
            }
        }
        //去除末尾空格
        while(res.back() == ' ') res.pop_back();
        return res;
    }
};
相关推荐
奔跑吧 android5 小时前
【linux kernel 常用数据结构和设计模式】【数据结构 2】【通过一个案例属性list、hlist、rbtree、xarray数据结构使用】
linux·数据结构·list·kernel·rbtree·hlist·xarray
汉克老师5 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(5、机甲战士)
c++·算法·蓝桥杯·01背包·蓝桥杯c++·c++蓝桥杯
Mr_Xuhhh6 小时前
项目需求分析(2)
c++·算法·leetcode·log4j
默默无名的大学生7 小时前
数据结构—顺序表
数据结构·windows
c++bug7 小时前
六级第一关——下楼梯
算法
PAK向日葵7 小时前
【C/C++】面试官:手写一个memmove,要求性能尽可能高
c语言·c++·面试
Morri37 小时前
[Java恶补day53] 45. 跳跃游戏Ⅱ
java·算法·leetcode
林木辛7 小时前
LeetCode热题 15.三数之和(双指针)
算法·leetcode·双指针
AndrewHZ7 小时前
【3D算法技术】blender中,在曲面上如何进行贴图?
算法·3d·blender·贴图·三维建模·三维重建·pcg
Jared_devin7 小时前
二叉树算法题—— [蓝桥杯 2019 省 AB] 完全二叉树的权值
数据结构·c++·算法·职场和发展·蓝桥杯