LeetCode151. Reverse Words in a String

Linux V4L2驱动开发实战:手把手教你用I2C摄像头Sensor注册一个v4l2_subdev 本文详细解析了Linux V4L2驱动开发中I2C摄像头Sensor注册v4l2_subdev的全流程,包括初始化、操作集填充、异步匹配等关键环节。通过实战案例和代码示例,帮助开发者掌握V4L2子系统下的摄像头驱动开发技巧,提升嵌入式Linux系统开发能力。 阅读详情
题目链接:

https://leetcode.com/problems/reverse-words-in-a-string/

题目描述:

将字符串逆转。

For example,
Given s = “the sky is blue”,
return “blue is sky the”.

需要注意的是开头,中间,结尾可能会有多余的空格。麻烦的就是去掉多余的空格。

分析:

用istringstream的话,会变得很简单。先贴上istringstream的解决方案吧。stringstream对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。这样就去掉了多余的空格。

第二种方法就是将每个单词先逆转了,最后再将整个字符串逆转。注意去掉多余空格。

第二个方法是参考别人的QAQ,找不到那篇文了,希望大神不要怪我没贴链接。

代码:

方法一:

class Solution {
public:
    void reverseWords(istringstream& ss,string &s){
        string word;
        if(ss>>word){
            reverseWords(ss,s);
            if(s==""){
                s=word;
            }
            else{
                s+=" "+word;
            }
        }
    }
    void reverseWords(string &s) {
        istringstream ss(s);
        reverseWords(ss,s="");
    }
};

方法二:

class Solution {
public:
    void reverse(string& s,int left,int right){
       while(left<right){
           char ch=s[right];
           s[right--]=s[left];
           s[left++]=ch;

       }
    }
    void reverseWords(string &s) {
        int len=s.size();
        int i=0,left=0,right=0;
        bool flag=false;
        while(i<len){
            while(i<len && s[i]==' '){
                i++;
            }
            if(i==len){
                break;
            }
            if(flag){
                s[right++]=' ';
            }
            left=right;
            while(i<len && s[i]!=' '){
                s[right++]=s[i++];
            }
            reverse(s,left,right-1);
            flag=true;
        }
        s.resize(right);
        reverse(s,0,right-1);
    }
};
C++ 小游戏程序 (共七款) C++编程小游戏_闪耀的天狼星的博客-优快云博客_游戏c++C++跑酷小游戏_闪耀的天狼星的博客-优快云博客。好玩的c++编程小游戏,共六款。代码】C++跑酷小游戏。 阅读详情

相关推荐

ST MCSDK V6.2.0实战:手把手教你配置HSO-ST观测器,体验500ms收敛的电机无感控制

本文详细介绍了ST MCSDK V6.2.0中HSO-ST观测器的配置方法,实现500ms内电流收敛的无感电机控制。从环境搭建、核心参数解析到无感启动优化,提供实战技巧和性能调优策略,帮助开发者快速掌握高效电机控制技术。

weixin_28720767的博客 579

Leetcod每日一题:151.reverse-words-in-a-string(翻转字符串里的单词)

思路是:双指针去头尾空格,然后遍历中间去空格到每个单词后最多一个空格;然后将整个字符串翻转,然后从头遍历将遇到的单词翻转回去; 一开始因为while (s[end] == ' ' && end >= 0) //除去结尾空格end>=0不严谨,导致案例" "死活不通过,我以为结果有问题,试了几次才发现end在这个案例中会减到-1,使得s[-1]这种溢出情况出现; 错误原...

CodeLuweir 的博客 2635

SPI模式下的SD卡读写,为什么你的数据总出错?详解时序与状态机避坑指南

本文深入探讨SPI模式下SD卡读写数据出错的根本原因,提供时序优化与状态机设计的实战指南。针对时钟周期计数、状态机跳转和忙检测等核心问题,详解命令时序细节、状态机同步策略及高级避坑技巧,帮助开发者提升SD卡在SPI模式下的稳定性和性能。

weixin_30514745的博客 261

Leetcode 151 Reverse Words in a String

lc151 Reverse Words in a String 利用split(),将String分成一个String[],可以用正则表达式"\\s+"(第一个\转义,\s表示空格,+表示多个空格),也可以直接用" ",第二种方法快一些 然后按题意翻转即可,从后面遍历String,一次将元素放入新String(这里可以用StringBuilder,会比直接用+连接字符串快,最后sb.toStr...

weixin_30609331的博客 103

1.Fay-UE5数字人工程导入(UE数字人系统教程)

ue5数字人系列教程(含源文件工程)

1万+

进程间通信的七种方法实战演示!值得收藏!

线程和进程间的通讯(Inter-Process Communication, IPC)是操作系统中的一个重要概念,用于实现不同进程或同一进程中的不同线程之间的数据交换和协调。以下是几个常见的进程间通信的方式:管道、消息队列、共享内存、信号、套接字、信号量、文件映射

十年饮冰,难凉热血,保持热爱,奔赴星海! 2816

【leetcode】【medium】【每日一题】151. Reverse Words in a String​​​​​​​

151. Reverse Words in a String Given an input string, reverse the string word by word. Example 1: Input: "the sky is blue" Output:"blue is sky the" Example 2: Input: " hello world! " Output...

lemonade13的博客 142

github创建账号第一步始终出错

github创建账号总结:第一次注册GitHub,填好用户名邮箱密码后进入下一步就卡在哪里,上面还提示Unable to verify your captcha response等,进入网址的解决办法以及下载其他的浏览器也无法解决,用手机浏览器抱着试一试的心态竟然成功了,分享给大家。手机下载谷歌浏览器,进入GitHub正常注册,能向下继续,邮箱验证完以后再用电脑登陆就ok啦

计算机毕业论文源码,学生个人网页制作html源码。贴近用户做网络推广和互联网优化。 4373

Task4:LeetCode1:twoSum; LeetCode344:Reverse String;LeetCode151:Reverse Words in a String

1.Two Sum(两个数求和) class Solution: def twoSum(self, nums: 'List[int]', target: int) -> 'List[int]': dicti = {} for i, n in enumerate(nums): if n in dicti: ...

m0_37548423的博客 168

2.1 直流无刷电机(BLDC):机械结构与组件

本文详细解析了直流无刷电机(BLDC)的机械结构与核心组件。BLDC电机通过电子换向取代传统机械电刷,主要包含定子、转子、位置传感器和电子换向器四大组件。定子采用硅钢片叠压结构,配有三相绕组;转子采用永磁体材料,结构设计影响转矩特性;位置传感器(霍尔、编码器、旋转变压器)实现精准换向;电子换向器通过功率逆变拓扑完成电流控制。文章还对比了不同绕组类型、永磁材料及传感器技术的性能特点,为BLDC电机的设计与应用提供了理论基础。

技术工作者 388

【ODX介绍】-5-用于Flash刷写的ODX-F文件概述

用于Flash刷写的ODX-F文件概述

「汽车电子助手」的博客 2531

LeetCode(151)Reverse Words in a String

题目如下: Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". 分析如下:         很基础的题目,需要考虑各种corner cases,比如下列: 1 "

BUILD 4466

026、传感器校准:加速度计校准

本文详细介绍了无人机飞控系统中加速度计的校准方法。作者从一次炸机事故引入,强调加速度计校准的重要性。文章首先解释了加速度计测量原理和误差来源,包括零偏、尺度因子和交叉轴耦合。重点介绍了两种校准方法:六位置法利用重力作为参考,操作简单但精度有限;椭球拟合通过采集大量数据点进行最小二乘拟合,精度更高但实现复杂。文章还指出温度补偿这一常被忽视的关键因素,并分享了实际调试中的经验教训,包括采样时长、安装误差、验证方法等。最后建议初学者从六位置法入手,逐步优化校准精度,强调良好的校准是飞控性能的基础。

2401_88858637的博客 45

【LeetCode】 151. Reverse Words in a String 翻转字符串里的单词(Medium)(JAVA)每日一题

【LeetCode】 88. Merge Sorted Array 翻转字符串里的单词(Medium)(JAVA) 题目地址: https://leetcode.com/problems/merge-sorted-array/ 题目描述: Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one s...

qq_16927853的博客 199

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

小练习 - LeetCode151 Reverse Words in a String的C语言解法

LeetCode 151. Reverse Words in a String 很适合练习C语言基础,练习一个OJ题目除了找最佳解法,还可以多想想刻意去练习一些数据结构等其他知识点,让练习举一反三。 Given an input string, reverse the string word by word. Example: Input: “the sky is blue”, Output: ...

Life runs on code 673

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【LeetCode】151. Reverse Words in a String

LeetCode151 传送门 一种解法: 容易想到两次遍历的方法。第一次遍历分词,第二次遍历反向拼接单词成为句子。然后可以将两次遍历改进为一次遍历。首先初始化一个空字符串s_rev,初始化指针end为原字符串最后一个位置加一。倒序遍历原字符串s,若s[i]为空格,则赋值end为i。否则,如果i - 1位置为空格,或i为0位置,则令s_rev拼接s[i:j]。但该方法没有使用pytho...

weixin_42344158的博客 264

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

LeetCode 151 Reverse Words in a String

思路1 不用split和trim函数。使用一个stack来从前往后存储单词,最后再依次pop出来即可。 复杂度 时间复杂度O(n), 空间复杂度O(n) 代码 class Solution { public String reverseWords(String s) { if(s.length() == 0) return ""; S...

我要上岸的博客 211

[Leetcode] 151. Reverse Words in a String

link: https://leetcode.com/problems/reverse-words-in-a-string/ Solution: split + reverse class Solution { public String reverseWords(String s) { if(s.length() == 0) return s; Strin...

Renoler的博客 139

leetcode 151 Reverse Words in a String (python)

Python Reverse Words in a String

快递小可的博客 2013

Leetcode 151题 Reverse Words in a String

Leetcode 151题 Reverse Words in a String

《致青春》——云梦泽 1103

[每日算法] leetcode第151题 Reverse Words in a String

原题目描述 Given an input string, reverse the string word by word. Example: Input: “the sky is blue”, Output: “blue is sky the”. Note: A word is defined as a sequence of non-space characters. Input stri...

大葱敏的博客 3557

【leetcode】151. Reverse Words in a String

解题思路: 双指针 提交代码: class Solution { public String reverseWords(String s) { if(s==null||s.length()==0) return s; String res=""; int p1=s.length()-1,p2; while(p1&gt;=0&amp;&amp;s.charAt(p1)=='...

AXIMI的博客 386

[Leetcode] 151. Reverse Words in a String 解题报告

题目: Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Update (2015-02-12): For C programmers: Try to solve it in

魔豆(Magicbean)的博客 884

LeetCode 151. Reverse Words in a String

题目来源:https://leetcode.com/problems/reverse-words-in-a-string/ 问题描述 151.Reverse Words in a String Medium Given an input string, reverse the string word by word. Example 1: Input: "the sky is blu...

da_kao_la的博客 150

[leetcode] 151. Reverse Words in a String 解题报告

题目链接:https://leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". U

小榕流光的专栏 3052
上一篇: LeetCode71. Simplify Path
下一篇: LeetCode93. Restore IP Addresses
_IanXiao
博客等级 码龄12年 84粉丝 241原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值