422. Length of Last Word【LintCode java】

Description

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.

A word is defined as a character sequence consists of non-space characters only.

Example

Given s = "Hello World", return 5.

解题:返回最后一个单词,注意是要用一个变量缓冲一下,否则一个字符串的最后几个字符为空时,可能会丢失数据。代码如下:

public class Solution {
    /**
     * @param s: A string
     * @return: the length of last word
     */
    public int lengthOfLastWord(String s) {
        // write your code here
        int count = 0;
        int res = 0;
        for(int i = 0; i < s.length(); i++){
            if( Character.isLetter(s.charAt(i)) ){
                count++;
            }else {
                res = count;
                count = 0;
            }
        }
        if(count != 0)
            return count;
        else 
            return res;
    }
}

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9330336.html
今日推荐