Wednesday, October 16, 2013

Solution to LeetCode Problems: Length of Last Word

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.
Thoughts:
The straightforward thought is that we can iterate the string to the end and reverse-iterate the string until we get the last word. The time complexity is O(2n).

To reduce the time complexity to O(n), we can iterate it only once and record the word length we are meeting. When we found a space, the word length is then backuped and we can start a new recording. However, if two or more continuous spaces are found, special care is required.
Solution:

  1. class Solution {  
  2. public:  
  3.     int lengthOfLastWord(const char *s) {  
  4.         int last_word_length=0;  
  5.         int this_word_length=0;  
  6.         const char* p=s;  
  7.         while(*p!=0)  
  8.         {  
  9.             if (*p++ == 32 )  
  10.             {  
  11.                 if (this_word_length != 0)  
  12.                     last_word_length = this_word_length;  
  13.                 this_word_length = 0;  
  14.             }  
  15.             else  
  16.                 ++this_word_length;  
  17.         }  
  18.         if (this_word_length == 0)  
  19.             return last_word_length;  
  20.         else  
  21.             return this_word_length;  
  22.     }  
  23. };  

No comments:

Post a Comment