美文网首页
58. Length of Last Word

58. Length of Last Word

作者: YellowLayne | 来源:发表于2017-06-16 14:23 被阅读0次

    1.描述

    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.

    For example,
    Given s = "Hello World",
    return 5.

    2.分析

    简单的字符串处理。

    3.代码

    int lengthOfLastWord(char* s) {
        if (NULL == s || 0 == strlen(s)) return 0;
        
        unsigned int length_of_s = strlen(s);
        unsigned int length_of_LW = 0;
        int flag = 0;  //0表示未找到单词,1表示找到并在搜索,2表示搜索完毕
        for (int i = length_of_s-1; i >= 0 && 2 != flag; --i) {
            if (0 == flag && ' ' == s[i]) continue;
            if (1 == flag && ' ' == s[i]) {
                flag = 2;
                continue;
            }
            if (0 == flag) flag = 1;
            ++length_of_LW;
        }
        return length_of_LW;
    }
    

    相关文章

      网友评论

          本文标题:58. Length of Last Word

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