lintcode-easy-Length of Last Word

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-easy-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.

Example

Given s = "Hello World", return 5.

Note

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

public class Solution {
    /**
     * @param s A string
     * @return the length of last word
     */
    public int lengthOfLastWord(String s) {
        // Write your code here
        if(s == null)
            return 0;
        
        String str = s.trim();
        if(str.length() == 0)   
            return 0;
        
        int count = 0;
        int index = str.length() - 1;
        
        while(index >= 0 && str.charAt(index) != ‘ ‘){
            count++;
            index--;
        }
        
        return count;
    }
}

 

以上是关于lintcode-easy-Length of Last Word的主要内容,如果未能解决你的问题,请参考以下文章

CF1109A Sasha and a Bit of Relax

HDU - 5381 The sum of gcd(莫队/线段树区间合并)

快速幂——L - Fantasy of a Summation LightOJ - 1213

关于python list index out of range

HDU - 5381 The sum of gcd(莫队/线段树区间合并)

Hdu5381 the sum of gcd(莫队)