当前位置:网站首页>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
边栏推荐
猜你喜欢

C#/VB.NET: extracted from the PDF document all form

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

无需破解,官网安装Visual Studio 2013社区版

QT basic functions, signals, slots

MySQL数据库————流程控制

What is the JVM runtime data area and the JMM memory model

8月微软技术课程,欢迎参与

QT commonly used global macro definitions
Stop using MySQL online DDL

How to use the Golang coroutine scheduler scheduler
随机推荐
一加OnePlus 10RT出现在Geekbench上 产品发布似乎也已临近
How opencv implements image skew correction
C语言理论--笔试面试基础稳固
2022年 PHP面试问题记录
在Map传值与对象传值中模糊查询
电商库存系统的防超卖和高并发扣减方案
B002 - Embedded Elderly Positioning Tracking Monitor
XAML WPF item groupBox control
食品安全 | 新鲜食品vs速食食品,哪一种是你的菜?
想随时、随地、随心使用数据库的朋友们,全体注意!
Use of message template placeholders
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) 题解
Go GORM事务实例分析
塔防海岸线用户协议
QPalette palette, frame color fill
EpiSci|片上系统的深度强化学习:神话与现实
How to make the fixed-point monitoring equipment display the geographic location on the EasyCVR platform GIS electronic map?
ExcelPatternTool: Excel表格-数据库互导工具
QT常用全局宏定义
阿里云的域名和ip绑定