Friday, March 8, 2013

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.
*/
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(s[0]==NULL) return 0;
        int i = 0;
        int posLastSpace = -1;
        int posFirstSpace = -1;
        int posWord = -1;
        if(s[0]!=' ') posWord = 0;
        while(s[i]!=NULL){
           if(s[i]==' ') posFirstSpace = i;
           while(s[i]==' '){
             posLastSpace = i;
             i++;
             if(s[i]!=NULL && s[i]!=' ') posWord = i;
           }
           if(s[i]!=NULL) i++;
        }
       
        if(s[i-1]==' '){
          if(posWord!=-1) return posFirstSpace-posWord;
          return 0;
        }
        else return i-posWord;
    }
};

No comments:

Post a Comment