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
.
源代码如下
C++:
#include <iostream>
#include <cstring>
using namespace std;
int lengthOfLastWord(const char *s)
{
int len = strlen(s);
int count = 0;
for(int i=len-1;i>=0;i--)
{
if(s[i] != ' ')
count++;
if(s[i] == ' ' && count !=0) //“ ”多个空字符时返回0
break;
}
return count;
}
int main()
{
char case1[] = "Hello World";
char case2[] = "abc";
char case3[] = " ";
char case4[] = " ";
char case5[] = " a";
cout << lengthOfLastWord(case2) << endl;
return 0;
}
Java:
public int lengthOfLastWord(String s) {
String parts[] = s.split(" ");
if(parts.length == 0) //空串返回0
return 0;
return parts[parts.length-1].length();
}