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;
    }
};
相关推荐
机器学习之心3 分钟前
MATLAB基于GA-ELM与NSGA-Ⅱ算法的42CrMo表面激光熔覆参数多目标优化
算法·matlab·ga-elm
TracyCoder1233 分钟前
LeetCode Hot100(17/100)——240. 搜索二维矩阵 II
算法·leetcode
FJW0208143 分钟前
haproxy的调度算法
算法
小程同学>o<4 分钟前
嵌入式之C/C++(二)内存
c语言·开发语言·c++·笔记·嵌入式软件·面试题库
浅念-4 分钟前
C语言——内存函数
c语言·经验分享·笔记·学习·算法
MicroTech202510 分钟前
微算法科技(NASDAQ:MLGO)基于后量子阈值算法的区块链隐私保护技术
科技·算法·区块链
qq_4171292516 分钟前
基于C++的区块链实现
开发语言·c++·算法
爱吃番茄鼠骗17 分钟前
指针函数的应用层与驱动层:解耦核心与实践
数据结构
2401_8324027519 分钟前
C++中的命令模式实战
开发语言·c++·算法
有一个好名字20 分钟前
力扣-钥匙和房间
算法·leetcode·深度优先