[Leetcode] Length of last word 最後一個單詞的長度
阿新 • • 發佈:2017-06-25
== length spa ast class define 跳過 要求 怎麽辦
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",
return5.
思路:要求最後一個單詞的長度,首先想到的當然是從後往前開始遍歷,若遇到空格或者下標等於0了,就返回單詞的個數就行,但是,這樣想忽略了一個問題,若是,字符串最後有空格怎麽辦?如: s ="Hello World ",所以應該是從後往前遍歷的時候,先跳過空格,直到遇到第一個非空格的字符,才開始計數。代碼如下:
1 class Solution { 2 public: 3 int lengthOfLastWord(const char *s) 4 { 5 int res=0; 6 int len=strlen(s); 7 if(s==NULL) return 0; 8 int i=len-1; 9 while(s[i]==‘ ‘) 10 i--; 11 while(s[i] !=‘ ‘&&i>=0) 12 { 13 i--; 14 res++; 15 } 16 return res; 17 } 18 };
[Leetcode] Length of last word 最後一個單詞的長度