博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Length of Last Word
阅读量:2195 次
发布时间:2019-05-02

本文共 1465 字,大约阅读时间需要 4 分钟。

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.

求字符串最后一个单词的长度

1. 之前考虑不全, 当只用一个length时,会出现'a '时判断错误, 于是要用两个标志来指明

2. 其实也可以先求长度, 从后往前就是求第一个单词的长度

class Solution {public:    int lengthOfLastWord(const char *s) {        int length1  = 0;        int length2  = 0;        int i,j;        char c;        while(*s!='\0')        {            if(*s++!=' ')                 length1++;            else if(length1!=0)            {                length2 = length1;                 length1 = 0;            }        }        if(length1!=0)            return length1;        if(length1==0)            return length2;    }};

这个是从尾到头, 直接求第一个单词长度,这样就是最后一个的长度了

有几点:

1. const char *p如果不加const就会报错, 类型不一样

2. s + lenght - 1; 这里要减1

class Solution {public:    int lengthOfLastWord(const char *s) {       int length = strlen(s);       int i;       int len = 0;       const char *p = s  + length - 1;       while(length--)       {        if(*p!=' ')        {            len++;            p--;        }        else if(len!=0)                break;            else                {                    p--;                    continue;                }       }        return len;    }};

转载于:https://my.oschina.net/vintnee/blog/640485

你可能感兴趣的文章
【Python】用Python打开csv和xml文件
查看>>
【Loadrunner】性能测试报告实战
查看>>
【自动化测试】自动化测试需要了解的的一些事情。
查看>>
【selenium】selenium ide的安装过程
查看>>
【手机自动化测试】monkey测试
查看>>
【英语】软件开发常用英语词汇
查看>>
Fiddler 抓包工具总结
查看>>
【雅思】雅思需要购买和准备的学习资料
查看>>
【雅思】雅思写作作业(1)
查看>>
【雅思】【大作文】【审题作业】关于同不同意的审题作业(重点)
查看>>
【Loadrunner】通过loadrunner录制时候有事件但是白页无法出来登录页怎么办?
查看>>
【English】【托业】【四六级】写译高频词汇
查看>>
【托业】【新东方全真模拟】01~02-----P5~6
查看>>
【托业】【新东方全真模拟】03~04-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST05~06-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST09~10-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST07~08-----P5~6
查看>>
solver及其配置
查看>>
JAVA多线程之volatile 与 synchronized 的比较
查看>>
Java集合框架知识梳理
查看>>