如何判断一段字符串最后一个单词及其长度?

HWOJ 计算字符串最后一个单词长度 HWOJ计算字符串最后一个单词长度 题目:计算字符串最后一个单词的长度,单词以空格隔开 输入样例: hello world 输出样例: 5 题目分析: ①由于题目中输入的字符串有空格,所以我们这里不能用scanf输入,我们采用gets(s) ②我们要检测最后一个单词的长度,也就是可以说明我们可以从后面往前面循环找出第一个空格位置,之后直接求差值我们就可以知道这个字符串最后一个单 阅读详情
package lastletter;
/**
 * 
 * 题目:
 *      对于字符数组,求最后一个单词的长度。
 *	s = "Hello World" --->World、长度5
 *      
 */
public class LastLetter {

	public static void main(String[] args) {
		String str = "Hello2222World";
		System.out.println(lastLetter(str));
		System.out.println(lastLetter(str).length());
	}
	public static String lastLetter(String str){
		int len = str.length();//取字符串的长度
		String result = "";
		for(int i=len-1;i>=0;i--){//循环
			char j = str.charAt(i);
			if(j>'a'&&j<'z'||j>'A'&&j<'Z'){//当为字母时,条件为true
				result=j+result;
			}else{
				break;//条件为否时,跳出循环
			}
		}
		return result;//返回字符串
	}
}
结果:
World
5
如果用正则表达式,非字母来分割的(String-split),分割的效率比较低,多了很多没有必要的判断!

计算字符串最后一个单词的长度,单词以空格隔开 牛客网华为机试刷题笔记 JAVA 1.字符串最后一个单词的长度 题目描述 计算字符串最后一个单词的长度,单词以空格隔开。 输入描述: 一行字符串,非空,长度小于5000。 输出描述: 整数N,最后一个单词的长度。 解题代码 import java.util.*; public class Main{ public static void main(String[] args){... 阅读详情

相关推荐

C++ 计算字符串最后一个单词的长度,单词以空格隔开。

题目描述 计算字符串最后一个单词的长度,单词以空格隔开。 输入描述: 一行字符串,非空,长度小于5000。 输出描述: 整数N,最后一个单词的长度。 示例1 输入`` hello world 输出 5 #include<iostream> #include<string> using namespace std; int main() { string s; ...

zhenmtwx的博客 1327

shell 单词末尾家字符_58、最后一个单词的长度

题目描述今天这个题我一开始的想法是:设立一个计数器count=0,从第一个单词开始统计,每前进一个字符,count ++。当遇到空格的时候,count清0,遍历完一遍以后,正好可以求出最后一个单词的长度。同时,也考虑了边界条件:s.length()==0和s[0]==' '返回0的情况,但是一直是解答错误。后来看了题解,我才恍然大悟,原来,这个字符串末尾也可以跟上有限个空格啊,比如“a ab ...

weixin_39577964的博客 154

字符串最后一个单词的长度

计算字符串最后一个单词的长度,单词以空格隔开。 输入 一行字符串,长度小于128。 输出 整数N,最后一个单词的长度。 样例输入 hello world

shell命令提取文件里以某字符结尾的单词

假设有一个文件,想提取里面的以字符b结尾的单词,文件中的单词之间可能有空格、tab或多个空格。 示例文件: $ cat a.log aaaa a ssss ddddd 12dd aaab ccc asdb 1111 asdsad bbbb aaassd bbbbb bbbaba 脚本: $ cat x.sh for ii in `cat a.log` do if [[ "$ii" =~ b$ ]]; then echo $ii fi done 结果: $ b

null 2254

IAR调试CC1310的错误:Fatal error:Failed to connect to the XDS emlulator (Error -241 @ 0x0:)

从simplelink_cc13x0_sdk_2_10_00_36导入collector工程后,rebuild后进行debug,出现了如图错误:Fatal error:Failed to connect to the XDS emlulator (connect ICEPick)...(Error -241 @ 0x0)A router subpath could not be accessed....

qq_40417648的博客 6228

Python实现支付宝转账接口

由于工作需要使用python开发一个自动转账接口,记录一下开发过程。 首先需要在蚂蚁金服上申请开通开发者账户,有了开发者账户就可以使用沙箱进行开发了。 在开发之前我们需要在沙箱应用中填写密钥,密钥的获取可以使用阿里提供的工具包自动生成。 前期准备工作完成了,接下来是编写代码部分。主要用到了python-alipay-sdk库,使用pip安装即可,如果安装的过程中遇到问题推荐使用Anaconda...

FanMLei的博客 8517

字符串最后一个单词的长度【Java】

计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。

h461415832的博客 1951

Oracle恢复学习实战小结

     学习oracle10g 043课程有段时间了,前一两个星期学习了backup/restore相关的内容,刚好公司有要求要为host服务器做一个备用机以防止数据意外丢失。于是,实战开始了。     首先介绍host服务器架构。host以oracle数据库作为底层数据存储,以公司总部开发的Santorin作为应用,主要提供给测试台架数据存储、数据访问、数据导入导出、用户权限管理和数据自动备份

kseawolfk的专栏 1036

LeetCode:58.最后一个单词的长度

解题思路: 标签:字符串遍历 1.从字符串末尾开始向前遍历,其中主要有两种情况 2.第一种情况,以字符串"Hello World"为例,从后向前遍历直到遍历到头或者遇到空格为止,即为最后一个单词"World"的长度5 3.第二种情况,以字符串"Hello World "为例,需要先将末尾的空格过滤掉,再进行第一种情况的操作,即认为最后一个单词为"World",长度为5 4.所以完整过程为先从后过滤掉空格找到单词尾部,再从尾部向前遍历,找到单词头部,最...

m0_52510770的博客 2307

Linux Wireless之80211(nl80211, cfg80211, mac80211)

Linux Wireless之80211(nl80211, cfg80211, mac80211)前言在Linux无线子系统中,cfg80211、mac80211和nl80211是三个关键的组件,它们共同工作以实现对802.11设备的配置和管理。cfg80211负责内核空间的通用API,mac80211负责具体的MAC层实现,而nl80211则作为用户空间与内核空间之间的桥梁,用于配置管理和通信。Netlink 是一个 Linux 中的 socket 类型,用于在内核与用户空间之间传递事件。

DD'Notes 1484

GAMES101:MacOS作业环境搭建

查看gcc/clang的位置产看gcc/clang的版本1.1.2 安装cmake。

weixin_38844255的博客 719

力扣58.最后一个单词的长度

最开始考虑从最后一个往前找,找到第一个空来确定单词的起始位置 代码: int lengthOfLastWord(char * s){ int count=0; bool flag=false; for(int i=strlen(s)-1;i>=0;i--){ if(s[i]==' ') break; else{ count++; } } return count

lamycies的博客 81

EXCEL VBA 导出高清图片方法

EXCEL VBA 导出高清图片方法 将EXCEL表格内容另存为图片的方法有很多种,简单的比如“复制为图片格式并另存”,“打印成XPS”等等,本文着重的是利用VBA实现的方法。 该方法适合用于中大型图文表格输出为图片格式,方便传阅,在office2010及以上版本最为流畅。 具体看代码: Sub printA4() Dim rng As Range '定义截图范围变量 'm = 20...

nfser_burn7的专栏 1万+

最后一个单词的长度——记录(C++)

class Solution { public: int lengthOfLastWord(string s) { int ml=0; int l=0; for(int j=0;j<s.length();j++) { if(s[j]!=' ') { ++l; } else if(l!=0) .

weixin_52958356的博客 76

VMware Horizon 8 2111 部署系列(九)创建即时克隆桌面池

即时克隆桌面池是在 vCenter Server 中使用 vmFork 技术(称为即时克隆 API)从最佳配置映像创建的自动桌面池。即时克隆共享同一个基础映像虚拟机,使用基础映像虚拟机的快照创建的,它使用的存储空间也少于完整虚拟机。 即时克隆始终保持开机状态,并在注销后从当前发布的映像重新创建。...

白昼的技术专栏 4047

肺癌术后随访离散选择实验(DCE)设计与SAS实现

随着肺癌早期诊断和治疗技术的进步,肺癌患者的生存率显著提高,术后随访管理成为提升患者生活质量的关键环节。然而,如何在有限的医疗资源下设计出既符合患者需求又具有成本效益的随访方案,是临床决策面临的重要挑战。 离散选择实验(Discrete Choice Experiment, DCE)是一种定量研究方法,通过模拟真实世界的选择情境,测量患者对不同随访方案属性的偏好程度。本研究旨在通过DCE方法,系统评估肺癌术后患者对随访服务的偏好,为制定以患者为中心的随访策略提供循证依据。

huanghm88的专栏 101

华为机试HJ1 字符串最后一个单词的长度

今天开始记录自己刷题的过程。首先看一下题。

bingw0114的博客 1082

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

计算字符串最后一个单词的长度,单词以空格隔开。

001-华为机试-在线训练 题目描述 计算字符串最后一个单词的长度,单词以空格隔开。 输入描述: 一行字符串,非空,长度小于5000。 输出描述: 整数N,最后一个单词的长度。 示例1 输入 hello world 输出 5 具体代码 x = input() print(len(x.split()[-1])) 知识拓展 Python split()方法 描...

echo_1994的博客 5632

深度学习工具包 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")

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

【Java】字符串最后一个单词长度

计算字符串最后一个单词的长度,单词以空格隔开。 输入描述: 一行字符串,非空,长度小于5000。 输出描述: 整数N,最后一个单词的长度。 示例 输入 hello world 输出 5 package 牛客; import java.util.Scanner; public class 字符串最后一个字符长度 { public static int ChangDu(String str...

Bry'ce的博客 1664

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

HJ1 字符串最后一个单词的长度

计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。

Edison's 小宇宙 1万+
上一篇: JavaScript中Number没有直接截取小区位的方法?
下一篇: 使用递归输出1-100;9*9乘法表
zcoderz
博客等级 码龄10年 2粉丝 16原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值