[leetcode] 58. Length of Last Word

来源:互联网 发布:水果网络营销策划书 编辑:程序博客网 时间:2024/05/16 08:22

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.

解法一:

用std::reverse翻转string,然后打出第一个词。

class Solution {public:    int lengthOfLastWord(string s) {        if(s.size()==0) return 0;        reverse(s.begin(),s.end());        istringstream in(s);                string lastw; in>>lastw;        return lastw.size();            }};

解法二:

主要是要先将末尾的空格跳过。

class Solution {public:    int lengthOfLastWord(string s) {        int right = s.size()-1;        while(right>=0 && s[right]==' ') right--;        int count = 0;        while(right>=0 && s[right]!=' ')        { right--;        count++;        }        return count;            }};


0 0
原创粉丝点击