【力扣算法题】反转字符串中单词
题目介绍
给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入:s = “Let’s take LeetCode contest”
输出:“s’teL ekat edoCteeL tsetnoc”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii
题解
1. 开新空间(力扣官方解法1)
思路就是开一个同大小的字符串,然后找空格,发现空格之后倒序把单词插入到新字符串中,然后追加一个空格,一直这样下去就能又反转单词又保留空格
力扣官方C++源码:
string reverseWords(string s) {
string ret;
int length = s.length();
int i = 0;
while (i < length) {
int start = i;
while (i < length && s[i] != ' ') {
i++;
}
for (int p = start; p < i; p++) {
ret.push_back(s[start + i - 1 - p]);
}
while (i < length && s[i] == ' ') {
i++;
ret.push_back(' ');
}
}
return ret;
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/solution/fan-zhuan-zi-fu-chuan-zhong-de-dan-ci-iii-by-lee-2/
2. 存索引,原地反转单词(个人解法/力扣官方解法2)
首先原地翻转一个单词的代码我就不细说,详细可以参考我之前总结的另一题【力扣算法题】反转字符串
有了那样的抽象,我们只需要一个起始下标和一个结束下标,就可以反转一个句子中的一个单词,那么剩下的就简单了,找到空格,把单词一一分出来,然后分别反转,最后返回的就是操作好的结果
个人C++源码:
void reverseWord(string& s, int lo, int hi)
{
while(lo < hi)
{
std::swap(s[lo], s[hi]);
lo++;
hi--;
}
}
string reverseWords(string s) {
unsigned int lo = 0;
unsigned int hi = 0;
unsigned int len = s.size();
unsigned int i = 0;
while(i < len)
{
if(s[i] == ' ')
{
hi = i - 1;
reverseWord(s, lo, hi);
lo = i + 1;
}
i++;
}
hi = len - 1;
reverseWord(s, lo, hi);
return s;
}
力扣官方C++源码:
string reverseWords(string s) {
int length = s.length();
int i = 0;
while (i < length) {
int start = i;
while (i < length && s[i] != ' ') {
i++;
}
int left = start, right = i - 1;
while (left < right) {
swap(s[left], s[right]);
left++;
right--;
}
while (i < length && s[i] == ' ') {
i++;
}
}
return s;
}
// 作者:LeetCode-Solution
// 链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/solution/fan-zhuan-zi-fu-chuan-zhong-de-dan-ci-iii-by-lee-2/