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;
    }
};
相关推荐
卷无止境2 小时前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
_清歌2 小时前
DSpark 深度解读:DeepSeek-V4 如何用「半自回归」把推理速度提升 85%
算法
统计实现局2 小时前
SVD 的三步走:双对角化、Givens 收敛、排序
算法
躬行见万象2 小时前
《VLA 系列》UniLab 强化训练 | G1 机器人 |复现
算法
统计实现局2 小时前
对称不定分解(Bunch-Kaufman):为什么 Cholesky 不够用
算法
统计实现局2 小时前
dqrsl 拆解:拿着 QR 结果能算出哪 5 种东西
算法
卷无止境2 小时前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
统计实现局2 小时前
为什么 Cholesky 求逆比 Gauss-Jordan 快一倍——行列式溢出防护详
算法
To_OC14 小时前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode