最后一个单词的长度-leetcode

1. 地址

https://leetcode-cn.com/problems/length-of-last-word/

2. 思路

从尾往头算
第一个非空字符计数,一直算到空字符或者到头

3. 代码

class Solution {

    /**
     * @param String $s
     * @return Integer
     */
    function lengthOfLastWord($s) {
        if (empty($s)) {
            return 0;
        }

        $retCount = 0;
        $start = false;
        for ($i = strlen($s) - 1; $i >= 0; $i--) {
            if (!$start && $s[$i] != ' ') {
                $start = true;
            }
            if (!$start) {
                continue;
            }
            if ($start && $s[$i] != ' ') {
                $retCount ++;
            } else {
                break;
            }
        }

        return $retCount;
    }
}
posted @ 2020-06-05 10:22  吴丹阳-V  阅读(133)  评论(0编辑  收藏  举报