第五周:58. Length of Last Word

    xiaoxiao2021-03-25  101

    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.

    解题思路:从后面往前遍历,定义res记录字符的个数,如果是字符,res自增,遇到空格就跳出循环,返回res就为最后一个单词的长度,注意一点就是当最后一个字符为空格时,不应把它当做一个英文单词。

    代码:

    int lengthOfLastWord(char* s) { int slen=strlen(s); int res=0; while(s[slen-1]==' ') slen--; for(int i=slen-1;i>=0;i--) { if(s[i]==' ') break; res++; } return res; }

    转载请注明原文地址: https://ju.6miu.com/read-15999.html

    最新回复(0)