面试经典150题——Day21

编程入门 行业动态 更新时间:2024-10-21 14:21:48

面试<a href=https://www.elefans.com/category/jswz/34/1769979.html style=经典150题——Day21"/>

面试经典150题——Day21

文章目录

    • 一、题目
    • 二、题解

一、题目

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?

题目来源: leetcode

二、题解

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;}
};

更多推荐

面试经典150题——Day21

本文发布于:2023-12-03 11:17:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1654762.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:经典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!