[LeetCode] 58.Length of Last Word

MTK Linux Charger驱动分析(二) - power_supply_core.c 的核心作用可以概括为:提供统一的电源管理框架;管理电源设备注册、属性访问、事件通知;封装sysfs 接口和 uevent 通知,屏蔽硬件细节;驱动开发者只需要实现,不关心底层通知和接口细节。简单来说,它是电源子系统的“大脑和中枢”,具体的电池/充电器只是“信息源”。 阅读详情

Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.

If the last word does not exist, return 0.

给定一个字符串s由大/小写字母和空空格字符组成,返回字符串中最后一个单词的长度。
如果最后一个单词不存在,则返回0。

Example:

Input: “Hello World”
Output: 5

这道题很简单,几乎没有难度,之所以记录下来是因为有一种解法比较值得借鉴

这是一种直观的解法:

class Solution {
    public int lengthOfLastWord(String s) {
        int length = 0;
        boolean flag = false;
        for (int i = 0; i < s.length(); i++){
            if (s.charAt(i) == ' '){
                flag = true;
            }else{
                if (flag) {
                    length = 0;
                    flag = false;
                }
                length++;
            }
        }
        return length;
    }
}

这是比较值得借鉴的解法,这个解法巧妙地利用了 Java String 的内置方法 trim()
String.trim()用来去除 String 中的空格字符

class Solution {
    public int lengthOfLastWord(String s) {
            if(s == null)
                return 0;

            return s.trim().length() - s.trim().lastIndexOf(' ') - 1;
    }
}

善于利用语言的内置方法可以很好帮助我们解决实际问题,而不需要自己花时间去实现它

总结目前开源的视频生成/视频编辑大模型 随着Sora的爆火,视频生成和视频编辑受到了越来越多的关注。这篇博客总结一下目前开源的视频生成和视频编辑的大模型,并分析他们各自的优缺点,以及在自己进行科研任务或者工作中应该如何选用对应的开源模型,希望能给从事这一领域研究和使用的小伙伴们帮助。 阅读详情

相关推荐

通过JLink下载实现工控MCU批量烧录实战案例

利用JLink下载工具实现高效稳定的工控MCU批量烧录,提升产线效率。案例详细解析了脚本配置与自动化流程,突出jlink下载的可靠性和可扩展性,适用于大规模嵌入式部署场景。

weixin_30205153的博客 814

python写算法题:leetcode: 58. Length of Last Word

class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ ret=0 lastch = len(s)-1 for _ in xrange(len(s)): ...

244

Cadence HDL原理图库避坑指南:从Excel导入引脚到解决‘V- V+’报错(附FPGA实例)

本文详细介绍了Cadence HDL原理图库的高效构建与排错方法,重点讲解如何从Excel智能导入引脚数据并优化FPGA封装设计。通过数据预处理、智能导入和深度排错三个关键阶段,帮助工程师避免常见错误如‘V- V+’报错,提升设计效率和准确性。

weixin_28739079的博客 236

LeetCode58 Length of Last Word

详细见:leetcode.com/problems/length-of-last-word Java Solution: github package leetcode; public class P058_LengthOfLastWord { public static void main(String[] args) { System.out.println(new S

zxwtry的博客 359

vasp算表面吸附流程_VASP表面吸附计算实例分析

本文主要为了记录在学习Vasp计算过程中如何设置INCAR中的一些参数,并不着重讲解其含义,详见可自行到vasp官网查阅。其次关于建模部分也不做细致讨论,一般结构可从Materials Studio里自带的晶体数据库导出,或从三大数据库网站上下载:1、Materaials Project网址:https://materialsproject.org/(强烈推荐,邮箱注册即可使用)2、CCDC网址:...

weixin_39617669的博客 2240

如何让Arduino IDE支持你手里的STM32 nucleo开发板

Arduino IDE开发环境在默认情况下不支持STM32 NUCLEO开发板,只有通过添加附加开发板管理包才能使用。目前为止,只有一部分板子支持使用Arduino IDE开发环境进行开发,分别是 Nucleo F207ZG, Nucleo F429ZI, Nucleo F030R8, Nucleo F091RC, Nucleo F103RB, Nucleo F303RE, Nucl...

mzw72188552的专栏 8972

【leetcode c++】58 Length of Last Word

Length of Last Word Given a string s consists ofupper/lower-case alphabets and empty space characters ' ', return the length oflast word in the string. If the last word does not exist, return 0.

lif的博客 442

飞牛NAS1.1.19更新后SSH连不上?两步快速恢复连接

飞牛NAS1.1.19版本更新后SSH无法连接😟,实则是官方安全策略升级默认关闭了该服务,本文分享两步实操配置恢复SSH连接💻,还同步了官方的设备安全配置建议,帮助用户兼顾使用与设备防护🔒。

XiaoqiangClub的博客 2101

LeetCode58——Length of Last Word

LeetCode58——Length of Last Word 求出最后最后一个单词的长度。 提供两种方案。 方案1: 把子串按word保存在vector里面,这样求出vector最后一个元素的长度就可以了。 代码: class Solution { public: int lengthOfLastWord(string s) { auto it = s.begin(); w

上善若水 1039

基于Matlab的无迹卡尔曼滤波惯性导航与DVL组合导航

航天航空领域中的惯性导航是一种基于惯性测量单元(Inertial Measurement Unit,IMU)的导航方法,可以提供航向、速度和位置等信息。深度/速度测量器(Doppler Velocity Log,DVL)是一种常用的传感器,可用于测量水下航行器的速度。通过将DVL与无迹卡尔曼滤波相结合,可以实现高精度的组合导航。本文介绍了基于Matlab的无迹卡尔曼滤波(UKF)惯性导航与DVL组合导航的方法。以上是一种简化的示例代码,您可以根据实际应用需求进行相应的修改和优化。

DevSavantX的博客 418

VS2019项目使用CGAL6.1配置教程详细步骤

在VS2019项目中使用CGAL详细步骤

插件开发 331

leetcode || 58、Length of Last Word

problem: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0

hustyangju的足迹 722

OpenClaw 2026.3.13 踩坑实录:飞书HTTP协议降级Bug与多版本回归问题汇总

摘要:OpenClaw v2026.3.13存在多个严重回归问题,包括飞书API调用协议意外降级为HTTP导致连接失败(#46100)、本地Gateway诊断矛盾(#45504)及设备配对CLI命令失效等。该版本发布流程本身也存在异常,被迫以v2026.3.13-1标签重新发布。建议飞书用户回退至v2026.3.8稳定版,其他用户谨慎升级。本文详细记录了各Bug现象、影响范围及临时解决方案,并梳理了飞书通道的"多版本回归史",指出其根源在于架构变迁和测试覆盖不足。最后提供了包含配置备份、

Maynor的博客 869

【LeetCode】58. Length of Last Word

58. Length of Last Word Introduce Given a string s consists of upper/lower-case alphabets and empty sp...

roguesir的博客 816

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

深度学习工具包 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 58. Length of Last Word

一 题目 Given a stringsconsists of upper/lower-case alphabets and empty space characters' ', return the length of last word in the string. If the last word does not exist, return 0. Note:A word is...

bohu83的博客 275

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

[LeetCode]58. Length of Last Word

[LeetCode]58. Length of Last Word题目描述思路遇到空格,将计数器置为0 考虑字符串后多个空格的情况,加一个pre值,将count置0之前,检查count不为0,则将count赋给pre 最后返回,若count为0则返回pre,否则返回count代码class Solution { public: int lengthOfLastWord(string s)

Lcharon的博客 1629

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

leetcode 58 Length of Last Word C++

注意特殊情况。 int lengthOfLastWord(string s) { if(s.empty()) return 0; int right = s.size(); int left = right; while(left>0) { if(s[left-1]!=' ')

wcxdell的专栏 824

leetcode|58. Length of Last Word

问题描述:Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.If the last word does not exist, return 0.Note: A word is defi...

笔记本 369

Leetcode题解(5):L58/Length of Last Word

Leetcode题解(5):L58/Length of Last Word L58: Length of Last Word Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return th...

weixin_30653097的博客 67

闯关leetcode——58. Length of Last Word

leetcode第58题

方亮的专栏 774

LeetCode 58. Length of Last Word

Length of Last Word - LeetCode Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word in the string. If the last word does not exist, re...

zhaohaibo的博客 339

leetcode解题之58 # Length of Last Word Java版

leetcode解题之58 # Length of Last Word Java版

mine_song的博客 476

LeetCode String 58 Length of Last Word

58. Length of Last Word Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word in the string. If the last word does not exist, return 0....

Yi Jiao's Blog 183

leetcode python3 简单题58. Length of Last Word

1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第五十八题 (1)题目 英文: Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word (last w...

从此做一个俗人 298

leetcode【58】Length of Last Word

问题描述: Given a stringsconsists of upper/lower-case alphabets and empty space characters' ', return the length of last word (last word means the last appearing word if we loop from left to right) in...

fanyuwgy的博客 121

[LeetCode 58] Length of Last Word

题目链接:length-of-last-word /** * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does

瓦尔登湖 496
上一篇: [LeetCode] 38.Count and Say
下一篇: Maven项目中无法找到 xml文件或 properties文件等配置文件的解决方法
WhataNerd
博客等级 码龄11年 191粉丝 64原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值