美文网首页
LeetCode 58. Length of Last Word

LeetCode 58. Length of Last Word

作者: njim3 | 来源:发表于2018-08-23 15:22 被阅读15次

    题目

    Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
    If the last word does not exist, return 0.

    Note: A word is defined as a character sequence consists of non-space characters only.

    Example:

    Input: "Hello World"
    Output: 5

    解析

    本题看似十分简单,其中还是需要有注意的地方的。题目中要找的是最后一个word,即使用空格来区域最后一个word,但是需要注意的边缘情况如下,

    "Hello world" -> "world"
    "Hello world   " -> "world", 5
    "   Hello   " -> "Hello", 5
    "a   " -> "a", 1
    "      " -> 空的,即为0

    因此,如果单独从空格来定位的话,上述所得到的结果便不正确,需要找到最后一个非空格的字符,由该位置依次往前找,找到第一个空格位置,这个长度便是最后一个word的长度。

    代码(C语言)

    int lengthOfLastWord(char* s) {
        
        if (s == NULL)
            return 0;
        
        int len = (int)strlen(s);
        int wordLen = 0;
        bool isPassCh = false;       // 是否找到第一个非空格字符
        
        for (int i = len - 1; i >= 0; --i) {
            if (s[i] == ' ') {
                if (isPassCh) {
                    break;
                } else {
                    continue;
                }
            }
            
            isPassCh = true;
            ++wordLen;
        }
        
        return wordLen;
    }
    

    循环从后往前开始寻找,如果找到第一个空格,并且未找到第一个非空格字符,则继续寻找,找到第一个非空格字符,置true,加长度,再次找到空格字符,则停止,返回。如果一直未找到,则到首字符停止。最后返回word长度。

    相关文章

      网友评论

          本文标题:LeetCode 58. Length of Last Word

          本文链接:https://www.haomeiwen.com/subject/ovfmiftx.html