Leetcode PHP题解--D140 58. Length of Last Word


D140 58. Length of Last Word

题目链接

58. Length of Last Word

题目分析

给定一个字符串,返回最后一个出现的单词长度。

解题思路

遍历字符串,当遇到一个字符,其前一个字符是空格时才能重新计数。

最终代码

<?php
class Solution {

    /**
     * @param String $s
     * @return Integer
     */
    function lengthOfLastWord($s) {
        $len = 0;
        if($s == ''){
            return $len;
        }
        $str = str_split($s);
        $prev = NULL;
        foreach($str as $char){
            if($char != ' '){
                if($prev == ' '){
                    $len = 0;
                }
                $len++;
            }
            $prev = $char;
        }
        return $len;
    }
}

若觉得本文章对你有用,欢迎用爱发电资助。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode PHP题解--D139 38. Count and Say

>> 下一篇: slim-board 是基于 slimphp 的 PHP 简单社区论坛系统