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;
    }
};
相关推荐
迷途之人不知返14 分钟前
优先级队列:priority_queue
数据结构·c++
jieyucx17 分钟前
Go 零基础数据结构:顺序表(像「排抽屉」一样学增删改查)
java·数据结构·golang
曦夜日长18 分钟前
C++ STL容器string(一):string的变量细节、默认函数的认识以及常用接口的使用
java·开发语言·c++
代码中介商20 分钟前
C++ STL 标准模板库完全指南:从容器到迭代器
开发语言·c++·stl
winner888122 分钟前
C++ 构造函数、析构函数、虚函数、虚析构
开发语言·c++
想唱rap23 分钟前
应用层协议与序列化
linux·运维·服务器·网络·数据结构·c++·算法
许长安26 分钟前
protobuf 使用详解
c++·经验分享·笔记·中间件
重生之我是Java开发战士29 分钟前
【笔试强训】Week3:重排字符串,分组,DNA序列
算法
Soley29 分钟前
用 Boost.Log 封装一个更顺手的 C++17 日志库:GoodLog
c++
We་ct31 分钟前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·leetcode·typescript·动态规划