当前位置:网站首页>LeetCode 0151. Reverse a string of words
LeetCode 0151. Reverse a string of words
2022-08-01 18:20:00 【Tisfy】
【LetMeFly】151.颠倒字符串中的单词
力扣题目链接:https://leetcode.cn/problems/reverse-words-in-a-string/
给你一个字符串 s ,颠倒字符串中 单词 的顺序.
单词 是由非空格字符组成的字符串.s 中使用至少一个空格将字符串中的 单词 分隔开.
返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串.
注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格.返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格.
示例 1:
输入:s = "the sky is blue" 输出:"blue is sky the"
示例 2:
输入:s = " hello world " 输出:"world hello" 解释:颠倒后的字符串中不能存在前导空格和尾随空格.
示例 3:
输入:s = "a good example" 输出:"example good a" 解释:如果两个单词间有多余的空格,颠倒后的字符串需要将单词间的空格减少到仅有一个.
提示:
1 <= s.length <= 104s包含英文大小写字母、数字和空格' 's中 至少存在一个 单词
进阶:如果字符串在你使用的编程语言中是一种可变数据类型,请尝试使用 O(1) 额外空间复杂度的 原地 解法.
方法一:栈
Traverse each character from back to front,遇到非空格字符就入栈,遇到空格/Traverse to the beginning of the string It depends on whether the stack is empty
如果栈不空,Add the new word on the stack just after the answer string
添加方式为:(If the word is not the first word of the answer string,just add spaces.)Pop the stack one by one and add to the end of the answer string
- 时间复杂度 O ( n ) O(n) O(n),其中 n n nis the length of the original string
- 空间复杂度 O ( m ) O(m) O(m),其中 m m mis the maximum word length
AC代码
C++
class Solution {
public:
string reverseWords(string s) {
string ans;
stack<char> st;
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] != ' ')
st.push(s[i]);
if (s[i] == ' ' || !i) {
if (st.size()) {
if (ans.size())
ans += ' ';
while (st.size()) {
ans += st.top();
st.pop();
}
}
}
}
return ans;
}
};
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/126093751
边栏推荐
- 一加OnePlus 10RT出现在Geekbench上 产品发布似乎也已临近
- QT_事件类
- Detailed explanation of DBPack SQL Tracing function and data encryption function
- B005 - STC8 based single chip microcomputer intelligent street light control system
- WinRAR | 将多个安装程序生成一个安装程序
- COS 用户实践征文
- How many steps does it take to convert an ENS domain name into music?
- SQL function TO_DATE (1)
- Zabbix6.0钉钉机器人告警
- Leetcode73. Matrix Zeroing
猜你喜欢

B002 - Embedded Elderly Positioning Tracking Monitor

LeetCode 0152. 乘积最大子数组:dp + 原地滚动

Leetcode75. 颜色分类

【Day_12 0507】二进制插入

C language theory--a solid foundation for the written test and interview

JVM运行时数据区与JMM内存模型是什么

explain 各字段介绍

关于单应性矩阵的若干思考

How to use the Golang coroutine scheduler scheduler

解决MySQL插入不了中文数据问题
随机推荐
QT基础功能,信号、槽
LeetCode 0152. 乘积最大子数组:dp + 原地滚动
SQL函数 TO_DATE(一)
Prometheus的Recording rules实践
直播系统聊天技术(八):vivo直播系统中IM消息模块的架构实践
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) 题解
What is the JVM runtime data area and the JMM memory model
SQL function TO_DATE (1)
el-form-item prop属性动态绑定不生效如何解决
顺序表的简单描述及代码的简单实现
opencv如何实现图像倾斜校正
如何让固定点的监控设备在EasyCVR平台GIS电子地图上显示地理位置?
7月30号|来一场手把手助您打造智能视觉新爆款的技术动手实验
Stop using MySQL online DDL
QT_QDialog 对话框
阿里云的域名和ip绑定
How to make the fixed-point monitoring equipment display the geographic location on the EasyCVR platform GIS electronic map?
电商库存系统的防超卖和高并发扣减方案
QT_事件类
MySQL数据库————存储过程和函数