当前位置:网站首页>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 <= 104
s
包含英文大小写字母、数字和空格' '
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
边栏推荐
猜你喜欢
B011 - 基于51的多功能指纹智能锁
【Day_11 0506】 最近公共祖先
QLineEdit learning and use
7月30号|来一场手把手助您打造智能视觉新爆款的技术动手实验
B011 - 51-based multifunctional fingerprint smart lock
解决MySQL插入不了中文数据问题
Detailed explanation of DBPack SQL Tracing function and data encryption function
Prometheus的Recording rules实践
Solve the problem that MySQL cannot insert Chinese data
How opencv implements image skew correction
随机推荐
以消费场景为驱动的CMDB要怎么建?
How to solve the dynamic binding of el-form-item prop attribute does not take effect
ExcelPatternTool: Excel表格-数据库互导工具
QT commonly used global macro definitions
B005 - STC8 based single chip microcomputer intelligent street light control system
MySQL Lock wait timeout exceeded; try restarting transaction 锁等待
Break the performance ceiling!AsiaInfo database supports more than 1 billion users, with a peak of one million transactions per second
暑假第二周总结博客
odoo 编码规范(编程规范、编码指南)
SQL function TO_DATE (2)
C#/VB.NET:从 PDF 文档中提取所有表格
【报错】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat‘)
MySQL数据库————流程控制
B001 - 基于STM32的智能生态鱼缸
XAML WPF项目groupBox控件
Basic image processing in opencv
Leetcode71. Simplified Paths
odoo+物联网
AIOps智能运维的领跑者擎创科技正式入驻InfoQ 写作社区!
MySQL关系型数据库事务的ACID特性与实现方法