leetcode 反转单词

news/2024/7/3 16:12:27

想一下,我们将整个字符串都反转过来,那么单词的顺序指定是倒序了,只不过单词本身也倒序了,那么再把单词反转一下,单词不就正过来了。

所以解题思路如下:

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

举个例子,源字符串为:"the sky is blue "

  • 移除多余空格 : "the sky is blue"
  • 字符串反转:"eulb si yks eht"
  • 单词反转:"blue is sky the"

这样我们就完成了翻转字符串里的单词。

class Solution {
public:
    void removespace(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) {
        removespace(s);
        reverse(s.begin(),s.end());
        auto start=s.begin();
        int count=0;
                for(int i=0;i<=s.size();i++){
         if(s[i]==' '||i==s.size())
            {
             reverse(start,s.begin()+i);
             start=(s.begin()+i+1);
             
         }
        }
        return s;

    }
};


http://lihuaxi.xjx100.cn/news/2051010.html

相关文章

300分钟吃透分布式缓存-16讲:常用的缓存组件Redis是如何运行的?

Redis 基本原理 Redis 简介 Redis 是一款基于 ANSI C 语言编写的&#xff0c;BSD 许可的&#xff0c;日志型 key-value 存储组件&#xff0c;它的所有数据结构都存在内存中&#xff0c;可以用作缓存、数据库和消息中间件。 Redis 是 Remote dictionary server 即远程字典服务…

linux统计程序耗时和最大内存消耗

要统计某个程序整个生命周期的耗时和最大内存消耗&#xff0c;可以使用 /usr/bin/time 命令&#xff0c;它提供了详细的执行时间和资源使用信息&#xff0c;包括最大内存消耗。这个工具比 shell 的内置 time 命令提供更多的信息&#xff0c;特别适合于性能分析。 统计程序运行…

NVIDIA\CUDA\cudnn安装以及visual studio2022编译安装ceres2.2.0库

一、NVIDIA驱动安装 网址:官方驱动 | NVIDIA 因为本文之后需要visual studio2022进行编译&#xff0c;所以在安装NVIDIA\CUDA\cudnn之前你先得安装visual studio2022 点击NVIDIA控制面板&#xff0c;NVIDIA Control Panel 查看产品家族 根据产品家族选择驱动&#xff0c;点…

GPT润色指令

1. GPT润色指令 Below is a paragraph from an academic paper. Polish the writing to meet the academic style,improve the spelling, grammar, clarity, concision and overall readability. When necessary, rewrite the whole sentence. Paragraph &#xff1a;你的句子…

9.网络游戏逆向分析与漏洞攻防-游戏网络架构逆向分析-接管游戏连接服务器的操作

内容参考于&#xff1a;易道云信息技术研究院VIP课 上一个内容&#xff1a;游戏底层功能对接类GameProc的实现 码云地址&#xff08;master 分支&#xff09;&#xff1a;https://gitee.com/dye_your_fingers/titan 码云版本号&#xff1a;44c54d30370d3621c1e9ec3d7fa1e2a0…

服务器被攻击了我们能采取什么措施?

当服务器遭受攻击时&#xff0c;我们可以采取以下方式进行应对&#xff1a; 1. 实时监控&#xff1a;通过实时监控服务器的网络流量、CPU使用率、内存使用率等指标&#xff0c;可以及时发现异常情况并采取相应的措施。 2. 防火墙配置&#xff1a;配置防火墙规则&#xff0c;限…

【EAI 026】RoboGen: 通过自动数据生成管线实现机器人技能学习

Paper Card 论文标题&#xff1a;RoboGen: Towards Unleashing Infinite Data for Automated Robot Learning via Generative Simulation 论文作者&#xff1a;Yufei Wang, Zhou Xian, Feng Chen, Tsun-Hsuan Wang, Yian Wang, Zackory Erickson, David Held, Chuang Gan 作者单…

动态规划之第 N 个泰波那契数/三步问题【leetCode】【算法】

动态规划动态规划之第 N 个泰波那契数/三步问题 动态规划LeetCode题目第 N 个泰波那契数求解1求解2&#xff08;滚动数组&#xff09; 三步问题求解1求解2&#xff08;滚动数组&#xff09; 动态规划 如果问题是由重叠的子问题构成的&#xff0c;那就可以用动态规划&#xff08…