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

Summer vacation second week wrap-up blog
Detailed explanation of DBPack SQL Tracing function and data encryption function

Leetcode71. Simplified Paths

【Day_11 0506】 最近公共祖先

【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)

电商库存系统的防超卖和高并发扣减方案
OnePlus 10RT appears on Geekbench, product launch also seems to be approaching

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

日志工厂(详细)
随机推荐
2022年 PHP面试问题记录
Friends who want to use the database anytime, anywhere and as you like, all attention!
关于单应性矩阵的若干思考
B005 - STC8 based single chip microcomputer intelligent street light control system
成都理工大学&电子科技大学|用于强化学习的域自适应状态表示对齐
ACID Characteristics and Implementation Methods of MySQL Relational Database Transactions
Leetcode71. Simplified Paths
用VS2013编译带boost库程序时提示 fatal error C1001: 编译器中发生内部错误
【Day_10 0428】井字棋
亚马逊云科技Build On2022技能提升计划第二季——揭秘出海爆款新物种背后的黑科技
opencv syntax Mat type summary
【无标题】setInterval和setTimeout详解
【Day_09 0427】 另类加法
explain 各字段介绍
AIOps智能运维的领跑者擎创科技正式入驻InfoQ 写作社区!
突破性能天花板!亚信数据库支撑 10 多亿用户,峰值每秒百万交易
生命周期和作用域
The function realization of the national standard GB28181 protocol EasyGBS platform compatible with the old version of the inflow port
金鱼哥RHCA回忆录:CL210管理OPENSTACK网络--章节实验
QT_事件类