[LeetCode]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(const char *s) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
		if(s==NULL) return 0;
		int len=strlen(s);
		int left=-1;
		int right=len-1;
		bool flag=false;
		for(int i=len-1;i>=0;i--)
		{
			if(s[i]!=' ')
			{
				if(!flag)
				{
					right=i;
					flag=true;
				}
			}
			else if(flag)
			{
				left=i;
				break;
			}
		}
		if(!flag) return 0;
		return right-left;
    }
};

  

posted @ 2013-11-19 15:05  七年之后  阅读(215)  评论(0编辑  收藏  举报