博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
lintcode:Length of Last Word 最后一个单词的长度
阅读量:6914 次
发布时间:2019-06-27

本文共 1290 字,大约阅读时间需要 4 分钟。

题目:

给定一个字符串, 包含大小写字母、空格' ',请返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

样例

给定 s = "Hello World",返回 5

注意

一个单词的界定是,由字母组成,但不包含任何的空格。

解题:

利用正则确认是字母,向前走,当遇到不是字母的时候跳出程序,为了合适的跳出定义一个布尔值,是字母的时候是true,当不是字母同时布尔值是true时候跳出

Java程序:

public class Solution {    /**     * @param s A string     * @return the length of last word     */    public int lengthOfLastWord(String s) {        // Write your code here        int lenword = 0;        boolean left = false;        String match = "\\w";        for(int i= s.length()-1;i>=0;i--){            String str = s.substring(i,i+1);            if(left==true &&str.matches(match)==false){                break;            }            if(str.matches(match)){                lenword+=1;                left = true;            }                    }        return lenword;    }}
View Code

总耗时: 11524 ms

Python程序:

class Solution:    # @param {string} s A string    # @return {int} the length of last word    def lengthOfLastWord(self, s):        # Write your code here        lenword = 0        isAlpha = False        for i in range(len(s)-1,-1,-1):            tmp = s[i]            if isAlpha==True and tmp.isalpha()==False:                break            if tmp.isalpha():                isAlpha = True                lenword +=1        return lenword
View Code

总耗时: 483 ms

 

转载地址:http://jhncl.baihongyu.com/

你可能感兴趣的文章
POJ 2029--Get Many Persimmon Trees +DP
查看>>
Java——复选框:JCheckBox
查看>>
Effective OC : 1-5
查看>>
mock.js 使用教程
查看>>
查看mysql存储引擎
查看>>
Python网络资源 + Python Manual
查看>>
面试中经常会被问到的70个问题
查看>>
在VMware上面安装Solaris 10
查看>>
throw跟throws关键字
查看>>
Linq-批量删除方法
查看>>
关于微信网页调用js-sdk相关接口注意事项目(一级域名与二级域名互相干扰!!!)...
查看>>
第二十三节,不同数据类型在内存中的存址方式,及深浅拷贝
查看>>
PID入门的十五个基本概念
查看>>
用android模拟器Genymotion定位元素
查看>>
Navicat连接oracle,出现Only compatible with oci version 8.1 and&nb (转)
查看>>
BusyBox 简化嵌入式 Linux 系统【转】
查看>>
时钟频率的理解--笔记【原创】
查看>>
win10 进入安全模式的方法
查看>>
hdu 5783 Divide the Sequence 贪心
查看>>
man/ls/clock/date/echo笔记
查看>>