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
.
简单题,不过我刚开始少想了一种情况,就是“hello world ”后面有很多空格,但是最后一个单词还是world
所以我们要从第一个不是空格的字符开始判断,然后再到下一个空格停止。
1 class Solution { 2 public: 3 int lengthOfLastWord(string s) { 4 if(s=="") return 0; 5 int len=s.length(); 6 int i=len-1; 7 int count=0; 8 9 while(s[i]==' ') i--; 10 for(;i>=0;i--) 11 { 12 if(s[i]!=' ') count++; 13 else break; 14 } 15 return count; 16 } 17 };