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;
    }
};
相关推荐
302wanger23 分钟前
DeepSeek-V4.1-Flash-1017 免费用到1024,速来
算法
lisw0541 分钟前
微分与积分的本质区别解析
算法·数学建模·极限编程
xys_6781 小时前
深挖数据结构:树和二叉树(上)
数据结构·算法
BeiGuTing_code1 小时前
Java动态数组(一)
java·数据结构·windows
衍玊1 小时前
多路转接原理与应用
c++
Interview Aid1122 小时前
Google SWE Intern VO 面经:两轮 Coding,Follow-up 考察 BFS 状态
算法
琳达爱分享2 小时前
从单机令牌桶到集群限流:一次配额超发的复盘
后端·算法
range2 小时前
带TTL的LRU缓存的实现-字节手撕-26/10/19
算法
糖果豆豆2 小时前
n log n 到底从哪来?排序下界、2-SAT 与 3-SAT、停机问题,卡的是同一件事
算法·架构
地平线开发者2 小时前
【玩转 征程6 算法工具链:PTQ 工具篇】hb_verifier
算法·自动驾驶