地址:http://oj.leetcode.com/problems/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) {
int len = strlen(s), res = 0;
for(int i = len -1; i>=0; --i)
{
if(res && s[i]==' ')
{
return res;
}
if(s[i] != ' ')
{
++res;
}
}
return res;
}
};
SECOND TRIAL
class Solution {
public:
int lengthOfLastWord(const char *s) {
if(!s)
return 0;
int end = strlen(s)-1, ans = 0;
while(0<=end && *(s+end)==' ')
--end;
if(0>end)
return 0;
ans = end;
while(end>=0 && isalpha(*(s+end)))
--end;
return ans-end;
}
};
python:
class Solution :# @param s, a string# @return an integerdef lengthOfLastWord ( self , s ):ans = 0for i in range ( len ( s ) - 1 , - 1 , - 1 ):if ans and s [ i ] == ' ' :return ansif s [ i ] != ' ' :ans += 1return ans