当前位置:网站首页>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
边栏推荐
- Leetcode71. Simplified Paths
- 【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)
- XML配置
- MySQL 45 Talk | 09 How to choose common index and unique index?
- What is the implementation principle of Go iota keyword and enumeration type
- ACID Characteristics and Implementation Methods of MySQL Relational Database Transactions
- 消息模板占位符的使用
- EpiSci | Deep Reinforcement Learning for SoCs: Myth and Reality
- B001 - Intelligent ecological fish tank based on STM32
- 成都理工大学&电子科技大学|用于强化学习的域自适应状态表示对齐
猜你喜欢
随机推荐
LeetCode 0151.颠倒字符串中的单词
阿里云的域名和ip绑定
EpiSci | Deep Reinforcement Learning for SoCs: Myth and Reality
中信证券是国内十大券商吗?怎么开户安全?
The function realization of the national standard GB28181 protocol EasyGBS platform compatible with the old version of the inflow port
B011 - 基于51的多功能指纹智能锁
QT_QDialog dialog
Stop using MySQL online DDL
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) Solution
Use of message template placeholders
What is the JVM runtime data area and the JMM memory model
opencv实时人脸检测
【Day_09 0427】走方格的方案数
Three solutions: npm WARN config global --global, --local are deprecated. Use --location=global instead.
tooltip control
QT_QDialog 对话框
golang json 返回空值
SQL的ROUND函数用法及其实例
opencv syntax Mat type summary
XAML WPF项目groupBox控件









