题目分析:[[EVD]] - 剑指 Offer 58 - I. 翻转单词顺序https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/
简单描述:
- 翻转句子中单词的顺序,但单词内字符的顺序不变
限制🚫
- 无空格字符构成一个单词。
- 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
- 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
示例:
输入: "the sky is blue"
输出: "blue is sky the"输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
解题思路:
思路:
- #双指针 j记录单词尾位置,i记录单词头位置
- 利用sstream库的stringstream函数 #[[C++ STL]]
- 利用algorithm库中函数reverse(底层实现为元素交换) #[[C++ STL]]
效率:
- 时间复杂度
- 空间复杂度
代码:
- 双指针
class Solution
{
public:
/*双指针*/
string reverseWords(string s)
{
int i = s.size() - 1, j; // j记录单词尾位置,i记录单词头位置
string res = "";
while (i >= 0)
{
while (i >= 0 && s[i] == ' ')
--i;
j = i;
while (i >= 0 && s[i] != ' ')
--i;
if (i < j)
res += s.substr(i + 1, j - i) + " ";
}
res.pop_back();
return res;
}
};
- 库函数
class Solution
{
public:
string reverseWords(string s)
{
string res = "", temp;
stringstream ss(s);
while (ss >> temp)
res = temp + " " + res;
res.pop_back();
return res;
}
};