58. Length of Last Word

来源:互联网 发布:手机数据老是自动打开 编辑:程序博客网 时间:2024/05/16 12:21

原题:

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.

Example:

Input: "Hello World"Output: 5

即返回给定字符串最后一个单词的长度。单词之间用空格' ' 隔开。注意实验表明最后一个单词后面可以有空格。


解题思路:

先跳过尾部的空格,然后从尾部遍历,直到发现空格。


AC代码:

public int lengthOfLastWord(String s) {        int len = s.length();        if (len == 0) return 0;        int i = 0,ret = 0;        while (i < len && s.charAt(len - i - 1) == ' ') i++;//去除尾部空格        while (i + ret < len && s.charAt(len - i - ret - 1) != ' ') ret++;//计算最后一个字母长度        return ret;    }


原创粉丝点击