[leetcode.com]算法题目 - 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
.
1 class Solution { 2 public: 3 int lengthOfLastWord(const char *s) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int len = strlen(s); 7 if(0==len) return 0; 8 9 int last = len; 10 int first = 0; 11 while(last>0 && s[last-1]==' '){ 12 last--; 13 } 14 while(first<last && s[first]==' '){ 15 first++; 16 } 17 if(0==last) return 0; 18 19 int i; 20 for(i=last-1;i>=first;i--){ 21 if(s[i]==' ') break; 22 } 23 return (last-i-1); 24 } 25 };