58. Length of Last Word
来源:互联网 发布:java 解决高并发 编辑:程序博客网 时间:2024/06/06 02:04
Problem:
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.
题意是给定一个字符串,然后返回最后一个单词的长度,一个单词是指没有空格组成字符串。所以判断条件是以空格为主。需要注意一些情况是“Hello World ”这种类似的情况,在我的代码中,一开始写的时候是遇到空格就把长度置0准备计算下一个单词的长度。但是这样的话,结果会输出0,不正确。所以条件改为了遇到空格后,下一个字符不是空格,才置0。
Code:
class Solution {public: int lengthOfLastWord(string s) { int sum = 0; int length = s.length(); for (int i = 0; i < length; i++) { if (s[i] != ' ') { sum++; } if (i == length - 1) { break; } if (s[i] == ' ' && s[i + 1] != ' ') { sum = 0; } } return sum; }};
阅读全文
0 0
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58.Length of Last Word
- ts、js自定义方法,实现延迟
- flex布局1
- int (*p)[10] 和 int *p[10]的区别
- Spring RestTemplate get方式发送数据服务器端拿到为空
- IOS第三方库GPUImage添加到Xcode工程
- 58. Length of Last Word
- CodeChef Graphcnt:Counting on a directed graph(支配树)
- 视图观察者
- JS笔记 —— JS正则表达式大全
- LaTeX技巧一:如何在标题页面上创建背景图像?
- 使用原生js替换jQuery
- 深入理解c++笔记
- 总结一下linuxc常用操作命令
- Codeforces 848C Goodbye Souvenir