首页 > 代码库 > LeetCode Length of Last Word

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

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



给定一个字符串包括大小写字符和空格,输出最后一个单词。


思路:

先用trim删除前后的空格判断是否是空串或是只有空格的串。

然后删除从后往前数的空格。

最后从头遍历若遇到空格则令index = i+1;

用substring 导出子串即可。


public class Solution {
    public int lengthOfLastWord(String s) {
        String temp = s.trim();//过滤空串、只有空格的串
        if(temp.length()==0)
            return 0;
        int index=0;
        int len = s.length();
        while(s.charAt(len-1)==' ')//删除所有字符串后面的空格
        {
            len--;
        }
        
        for(int i=0;i<len;i++)
        {
            if(s.charAt(i)==' ')
                index=i+1;
        }
        String A = s.substring(index,len);
        return A.length();
    }
}




LeetCode Length of Last Word