LeetCode(58. 最后一个单词的长度)

版权声明:https://blog.csdn.net/San_South https://blog.csdn.net/San_South/article/details/81304885
算法描述 :
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

说明:一个单词是指由字母组成,但不包含任何空格的字符串。

示例:

输入: "Hello World"
输出: 5

算法实现 :

Java实现 :

class Solution {
    public int lengthOfLastWord(String s) {

        int count=0; // 统计最后一个单词的字符数
        for (int i=s.length()-1;i>=0;i--) {
            if (s.charAt(i)==' ') {
                continue;
            }

            // i>count 放前面, 否则 "a" 这样的字符串会越界
            while (i>=count && s.charAt(i-count)!=' ') {
                count++;
            }

            return count;
        }

        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/San_South/article/details/81304885
今日推荐