leetcode_Length of Last Word

来源:互联网 发布:js获取鼠标点击位置 编辑:程序博客网 时间:2024/05/20 11: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.s==null return 0

2.s=s.trim(),s.length()==0 return 0;

3.从后面开始计算字母的数量,直到遇到空格为止

代码:

 public int lengthOfLastWord(String s) {        if(s==null)            return 0;        s=s.trim();        int len=s.length();        if(len==0)            return 0;        int i=0;        for(i=len-1;i>=0;i--)        {            if(!isAlp(s.charAt(i)))                break;        }        return len-1-i;    }    public boolean isAlp(char ch)    {        if((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z'))            return true;        return false;    }


0 0
原创粉丝点击