58. 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
.
求最后一个单词的长度,要去掉最后多余的空格
C++(3ms):
1 class Solution { 2 public: 3 int lengthOfLastWord(string s) { 4 int len = s.length() ; 5 int res = 0 ; 6 int tail = len-1 ; 7 while(tail >= 0 && s[tail] == ' ') 8 tail-- ; 9 while(tail >= 0 && s[tail] != ' '){ 10 res++ ; 11 tail-- ; 12 } 13 return res ; 14 } 15 };
1 class Solution { 2 public: 3 int lengthOfLastWord(string s) { 4 int len = s.length() ; 5 int res = 0 ; 6 int i ; 7 for (i = len-1 ; i >= 0 ; i--){ 8 if (s[i] != ' ') 9 break ; 10 } 11 for(; i >= 0 ; i--){ 12 if (s[i] == ' ') 13 break ; 14 else 15 res++ ; 16 } 17 return res ; 18 } 19 };