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;
    }
};
相关推荐
kyle~10 分钟前
C++20--- concept 关键字 为模板参数提供了编译期可验证的约束机制
运维·c++
CS_浮鱼18 分钟前
【C++进阶】异常
开发语言·c++
阿林学习计算机19 分钟前
哈希表实现unordered_map
数据结构·哈希算法·散列表
努力学算法的蒟蒻24 分钟前
day14(11.14)——leetcode面试经典150
算法·leetcode
QT 小鲜肉28 分钟前
【C++基础与提高】第十一章:面向对象编程进阶——继承与多态
java·linux·开发语言·c++·笔记·qt
艾莉丝努力练剑28 分钟前
【C++:封装红黑树】C++红黑树封装实战:从零实现MyMap与MySet
c++·stl·set·map·红黑树·平衡二叉树
洛_尘38 分钟前
数据结构--6:优先级队列(堆)
java·数据结构
让我们一起加油好吗42 分钟前
【数据结构】并查集(操作详解 + 模板 + 练习)
数据结构·算法·并查集·洛谷
PenguinLeee1 小时前
KKT条件:对偶问题、KKT条件以及内点法
算法·凸优化
序属秋秋秋1 小时前
《Linux系统编程之进程基础》【进程入门】
linux·运维·c语言·c++·进程·系统编程·fork