当前位置: 首页 > article >正文

面试经典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;
    }
};

http://www.kler.cn/a/104275.html

相关文章:

  • C语言学习笔记(六):数组(1)
  • 热搜榜:最热门的话题文本排行榜API接口
  • C#中的日期时间比较和格式化的方法
  • 知识点滴 - Email地址不区分大小写
  • 超级强大!送你几款Linux 下终极SSH客户端
  • 5G vs 4G
  • Openssl数据安全传输平台004:Socket C-API封装为C++类 / 服务端及客户端代码框架和实现
  • DBOW概要理解与记录
  • 使用时间潜在瓶颈网络进行图像分类
  • XTU-OJ 1221-Binary
  • C++ 常用数学函数详解汇总#include<cmath>
  • 【python笔记】小甲鱼
  • Mybatis-Plus CRUD
  • npm 彻底卸载
  • ArcGIS中如何为跨带数据投影?
  • Elasticsearch核心技术与实战-05-elasticsearch的安装与简单配置-Windows
  • 【计算机网络笔记】网络应用对传输服务的需求
  • android button 按钮,设置左/右小图标,与文字居中距离
  • 华为OD机试 - 字符串加密(Java 2023 B卷 100分)
  • #力扣:2413. 最小偶倍数@FDDLC