Tuesday, April 16, 2013

Length of Last Word(C++ code)

LeetCode Length of Last Word, Mar 27 '12
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.

 思路:细节啊细节,俺细节一向很差。。

  int lengthOfLastWord(const char *s) {

   if(!s) return 0;
    int start = 0, cur = 0, length = 0;

   while(s[cur] != '\0'){

       if(s[cur] == ' ') {length = cur - start;

          while(s[cur] == ' ')cur++;
           if(s[cur] == '\0') return length;
          start = cur; continue;}   

           cur++;

   }

  return cur - start;
    
    }

No comments:

Post a Comment