mobile wallpaper 1
mobile wallpaper 2
mobile wallpaper 3
mobile wallpaper 4
179 字
1 分钟
LeetCode 面试经典150题 [21/150 反转字符串中的单词]
2024-06-20
2024-06-23

题目描述#

给你一个字符串 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"
解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。

个人C++解答#

class Solution {
public:
string reverseWords(string s) {
bool flag = false;
string str_ = "";
vector<string> result;
for (auto str : s) {
if (str != ' ') {
flag = true;
str_.push_back(str);
}
else if (str == ' ' && flag ) {
result.push_back(str_);
str_.clear();
flag = false;
}
}
if (flag && !str_.empty()) {
result.push_back(str_);
}
string reversed = "";
for (auto it = result.rbegin(); it != result.rend(); ++it) {
reversed += *it;
if (it + 1 != result.rend()) reversed += " ";
}
return reversed;
}
};
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

LeetCode 面试经典150题 [21/150 反转字符串中的单词]
https://ericonline.cn/posts/leetcode-面试经典150题-21-150-反转字符串中的单词/
作者
Eric
发布于
2024-06-20
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录