Leetcode 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

中文题意

输入为一个字符串s,s中只会包含大写字母、小写字母和空格三种内容,找到s中最后一个单词的字母个数。

是否为一个单词的判断标准为:没有空格符的连续字符串。

分析

关键是找到s中最后一个单词,从后向前找最便捷,从后向前遍历的过程中,找到非空格字符的前一个字符为空格字符就停止遍历。

注意:字符串的长度计算函数为:length()

         空字符的表示为'';空格字符的表示为' '

java代码

class Solution {
    public int lengthOfLastWord(String s) {
       int count = 0;
       int len = s.length();
        
       while(len > 0 && s.charAt(len -1) == ' '){
           len--;
       }
        
       while(len > 0 && s.charAt(len -1) != ' '){
           count++;
           len--;
       }
        
        return count;
        
    }
}

猜你喜欢

转载自blog.csdn.net/xingkong_04/article/details/80561702