LeetCode(58)-Length of Last Word

版权声明:XiangYida https://blog.csdn.net/qq_36781505/article/details/83616156

58. 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.
Example:
Input: “Hello World”
Output: 5

好吧,这个题很简单,给一个字符串,然后求出最后一个单词的长度

public int lengthOfLastWord(String s){
        int len=0;
        for (int i =s.length()-1; i>0; i--) {
            if(' '==s.charAt(i)){
                if(len==0)continue;
                return len;
            }
            len++;
        }
        return len;
    }

猜你喜欢

转载自blog.csdn.net/qq_36781505/article/details/83616156