首页 > 学院 > 开发设计 > 正文

LeetCode#58--LengthofLastWord(字符串最后一个单词的长度是多少)

2019-11-14 15:30:26
字体:
来源:转载
供稿:网友

题目:

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 defined as a character sequence consists of non-space characters only.

For example,
Given s = "Hello World",
return 5.

分析:

思路:遍历,遇到字母开始计数,遇到空格将计数清零,再从头开始计数。

考虑特殊情况三种情况:

1.整个字符串为空时

2.字符串由无数的空格组成时

3.字符串最后以空格结尾时

知识点总结:

1. if(s.substring(i,i+1).equals(" "))       //用来判断字符串s的第i个字符是否是空格

2.if (s.trim().isEmpty())         //trim的作用是去掉字符串左右两侧的空格,中间的干涉不了,用于检测字符串是不是由任意个空格组成

Accepted代码如下:

 

public int lengthOfLastWord(String s) {        int num=0;        int remember=0;//用来记住空格前面的那个字符,防止空格出现在最后        if(s.length()==0)                {                    return 0;                }        else if (s.trim().isEmpty()) {            return 0;//判断整个字符串是否全部为空格组成        }        else {        for(int i=0;i<s.length();i++){            num++;//用来计数,每次遇到空格则重新计数            if(num!=1)            {         remember=num;}        if(s.substring(i,i+1).equals(" ")){        num=0;//遇到空格置零即可        }            }        if(num==0){            return (remember-1);        }        else{return num;}                }        }

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表