58. Length of Last Word

来源:互联网 发布:周芷若结局 知乎 编辑:程序博客网 时间:2024/04/29 23:13

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.字符串末尾为空格字符' '

下面是代码:

public class Solution {    public int lengthOfLastWord(String s) {        int num = 0;        int k = s.length()-1;        while(k>=0 && s.charAt(k) == ' ')            k--;        if(k == -1) return 0;        for(int i=k;i>=0;i--){            if(s.charAt(i) != ' ')                num++;            else                break;        }        return num;    }}


如果灵活的利用Java自带的相关方法,我们可以使代码变得更加简洁,如下:
public int lengthOfLastWord(String s) {    return s.trim().length()-s.trim().lastIndexOf(" ")-1;}
是不是特别简单,Stirng的trim()方法返回的的是一个去除字符串两端空格的字符串。