leetcode 58. length of last word

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.

从头开始记录字符串的长度,如果是最后一个字符串输出。

class Solution {
public:
    int lengthOfLastWord(string s) {
        int n=s.length();
        int l=0;
        int l_pre=0;
        for(int i=0;i<n;i++)
        {
            
            if(s[i]==' ')
            {
                if(l!=0)
                l_pre=l;
                 l=0;
            }
               
            else l++;
        }
        if(l==0)
            return l_pre;
        else
        return l;
    }
};

  

只有后面是字符串的话,才改变length 为0

class Solution {
public:
    int lengthOfLastWord(string s) {
        int n=s.length();
        int l=0;
        bool start=true;
        for(int i=0;i<n;i++)
        {
            
            if(s[i]!=' ')
            {
                if(start) l=0;
                l++;   
                start=false;
            }
            else
                start=true;
               
        }
   
        return l;
    }
};

 

posted @ 2017-07-22 18:17  hahahaf  阅读(171)  评论(0编辑  收藏  举报