leetcode题目58. 最后一个单词的长度

题目描述

链接:https://leetcode-cn.com/problems/length-of-last-word/
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。

单词 是指仅由字母组成、不包含任何空格字符的最大子字符串

示例

输入:s = "Hello World"
输出:5

代码

    // 题解:https://leetcode-cn.com/problems/length-of-last-word/solution/zui-hou-yi-ge-dan-ci-de-chang-du-by-leet-51ih/
    public int lengthOfLastWord(String s) {
        if (s == null) {
            return 0;
        }
        // 反向遍历
        int i = s.length() - 1;
        while (i >= 0 && s.charAt(i) == ' ') {
            i --;
        }
        int res = 0;
        while (i >= 0 && s.charAt(i) != ' ') {
            res ++;
            i --;
        }
        return res;
    }

你可能感兴趣的:(leetcode题目58. 最后一个单词的长度)