58.leetcode Length of Last Word(easy)[字符串 分割]

来源:互联网 发布:linux安装vnc客户端 编辑:程序博客网 时间:2024/04/27 11:50

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.

返回字符串中最后一个单词的长度,因此这个题目可以采用下面的方式完成在字符串首部加上空格,那么每遍历到一个非空格字符那么前面的字符如果是空格那么step清零重新开始计算,否则增加step的值。也可以采用分割算法按照空格分隔字符串得到最后一个字符串,然后计算长度。

class Solution {public:    int lengthOfLastWord(string s) {        int step = 0;        int flag = 0;        string s1(" ");        s = s1+s;        for(int i=1;i<s.length();i++)        {            if(s[i] !=' ')            {                if(s[i-1]==' ')                    step = 0;                 ++step;            }        }        return step;    }};


0 0
原创粉丝点击