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
.
// test58lengthOfLastWord.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include "iostream"
#include "string"
using std::string;
int lengthOfLastWord(string s);
int _tmain(int argc, _TCHAR* argv[])
{
int n = lengthOfLastWord(" hello haha ");
return 0;
}
/*
總共幾種情況
"hello" " hello world" "hello wor" "hello haha " " "
*/
int lengthOfLastWord(string s)
{
int n = s.size();
if (n < 1)
return n;
int currentLen = 0;
int count = 0;
for (auto i = 0; i < n; i++)
{
if (s[i] == ' ')
{
if (count == 0)
continue;
else
{
currentLen = count;
count = 0;
continue;
}
}
count++;
}
if (count != 0)
currentLen = count;
return currentLen;
}