翻转字符串里的单词 II
翻转字符串里的单词 II
问题描述
给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
注意:
单词的定义是不包含空格的一系列字符
输入字符串中不会包含前置或尾随的空格
单词与单词之间永远是以单个空格隔开的
进阶:使用 O(1) 额外空间复杂度的原地解法。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-ii
思路
- 以空格为分隔,将每个单词提取出来。
- 按照单词之间的倒序顺序,但是单词内部的正常顺序,将单词存到ret中。
- 最后,返回ret即可。
题解
class Solution {
public:
void reverseWords(vector<char> &s) {
vector<char> ret;
string tmp;
vector<string> tmp1;
for (int i = 0; i < s.size(); i++) {
if (s[i] != ' ') {
tmp += s[i];
} else if (s[i] == ' ') {
tmp1.push_back(tmp);
tmp = "";
}
}
tmp1.push_back(tmp);
reverse(tmp1.begin(), tmp1.end());
for (int i = 0; i < tmp1.size(); i++) {
for (int j = 0; j < tmp1[i].length(); j++) {
ret.push_back(tmp1[i][j]);
}
if (i != tmp1.size() - 1) {
ret.push_back(' ');
}
}
s=ret;
}
};