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;    }};