反转字符串中的单词(力扣刷题)

简介: 反转字符串中的单词(力扣刷题)

给你一个字符串 s ,请你反转字符串中 单词 的顺序。


单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。


返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。


注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。


a84beef6a2244a6b9e5ebd781e5968c3.png


来源:力扣(LeetCode)

链接:https://leetcode.cn/problems/reverse-words-in-a-string

 

思路:

分为三步骤:

  • 移除多余空格
  • 将整个字符串反转
  • 将每个单词反转


实现代码:

class Solution {
public:
    //反转整体
    void reverse(string& s,int start,int end)
    {
        for(int i = start,j = end; i < j; i++, j--)
        {
            swap(s[i],s[j]);
        }
    }
    //去除多余空格
    void removeExtraSpaces(string& s)
    {
        int slow = 0;
        for(int i = 0; i < s.size(); i++)
        {
            if(s[i] != ' ')
            {
                if(slow != 0)
                {
                    s[slow++] = ' ';
                }
                while(i < s.size() && s[i] != ' ')
                {
                    s[slow++] = s[i++];
                }
            }
        }
        s.resize(slow);
    }
    //反转单词
    string reverseWords(string s) {
        removeExtraSpaces(s); //去除多余空格
        reverse(s,0,s.size() - 1);
        int start = 0;
        for(int i = 0; i <= s.size(); i++)
        {
            if(i == s.size() || s[i] == ' ')
            {
                reverse(s, start, i - 1);
                start = i + 1;
            }
        }
        return s;
    }
};


相关文章
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
2月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
2月前
|
算法
LeetCode刷题---21.合并两个有序链表(双指针)
LeetCode刷题---21.合并两个有序链表(双指针)
|
2月前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
|
2月前
|
算法 测试技术
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
|
2月前
|
存储
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
144 38
|
8天前
刷题之Leetcode160题(超级详细)
刷题之Leetcode160题(超级详细)
11 0
|
8天前
刷题之Leetcode206题(超级详细)
刷题之Leetcode206题(超级详细)
21 0
刷题之Leetcode206题(超级详细)

热门文章

最新文章