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;
    }
}

相关文章:

  • 2021-11-26
  • 2022-01-16
  • 2021-10-23
  • 2021-06-23
  • 2021-12-30
  • 2021-07-17
猜你喜欢
  • 2021-10-18
  • 2021-08-14
  • 2021-07-15
  • 2022-12-23
  • 2021-11-07
  • 2021-04-08
  • 2021-10-06
相关资源
相似解决方案