2013.12.21 01:48
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
.
Solution:
Search for the start and end position of the last word, the length is (end - start).
Note that there might be NO last word at all, return 0 then.
Time complexity is O(n), where n is the length of the string. Space complexity is O(1).
Accepted code:
1 // 1WA, 1AC 2 class Solution { 3 public: 4 int lengthOfLastWord(const char *s) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 if(s == nullptr){ 8 return 0; 9 } 10 11 int len = strlen(s); 12 13 if(len <= 0){ 14 return 0; 15 } 16 17 int i, j; 18 19 i = len - 1; 20 while(i >= 0 && s[i] == ' '){ 21 --i; 22 } 23 ++i; 24 25 // 1WA, index is wrong, not j = i, but j = i - 1 26 j = i - 1; 27 while(j >= 0 && s[j] != ' '){ 28 --j; 29 } 30 ++j; 31 if(i < 0 || j < 0 || i < j){ 32 return 0; 33 }else{ 34 return i - j; 35 } 36 } 37 };