Leetcode 58 Length of Last Word

来源:互联网 发布:微信商城源代码 php 编辑:程序博客网 时间:2024/05/16 19:23

题目要求:

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.

----------------------------------------------------------------------------------------------------------------------------------------

解答比较简单,唯一需要注意的是对在统计last word length前后,对空格的判断

代码如下:

class Solution {public:    int lengthOfLastWord(string s) {        int len = s.length();        if(len == 0)            return 0;                int k = 0;        int flag = 0;        for(int i = 0; i < len; i++)        {            if(s[len - i - 1] == ' ' && flag == 0)                continue;            else if(s[len - i - 1] == ' ' && flag == 1)                break;            else if(s[len - i - 1] != ' ')            {                k++;                flag = 1;            }        }        return k;    }};


0 0
原创粉丝点击