My simple solution in C++


  • 64
    E

    I've noticed that a lot of solutions use available library functions that return directly the positions of certain characters or do other operations like "split". I personally don't think that's a good idea. Firstly, these functions take some time and usually involve with iteration through the whole string. Secondly, questions like this one is intended to be a practice of detail implementation, not calling other functions. My solution like below uses only the most basic string operations and probably beats many other solutions which call other existing functions.

     int lengthOfLastWord(const char* s) {
            int len = 0;
            while (*s) {
                if (*s++ != ' ')
                    ++len;
                else if (*s && *s != ' ')
                    len = 0;
        
            }
            return len;
        }

  • -4
    D
    This post is deleted!

  • 0
    S

    It is too tricky to accept by interviewer.


  • -2
    H
    This post is deleted!

  • 0
    T

    What about the time your code consumed? We don't really know how stringstream was implemented.


  • 9
    H

    It is my Java solution that follows two step:

    1. ignore the tailing whitespace

    2. find the last word

      public int lengthOfLastWord(String s) {
      int len = 0; i = s.length()-1;

       //ignore the trailing whitespace
       for (; i >= 0 && s.charAt(j) == ' '; i--);
      
       for (; i >= 0 && s.charAt(j) != ' '; i--) {
           len++;
       }
       return len;
      

      }


  • 0
    Z
    This post is deleted!

  • 1
    Z

    My Java solution. It goes from the end to the beginning and stops after finding the word.

    public class Solution {
        public int lengthOfLastWord(String s) {
            if(s == null || s.length() == 0)
                return 0;
    
            int begin = -1, end = -1;
    
            for(int i = s.length()-1; i >= 0; --i) {
                if(end == -1 && !Character.isSpaceChar(s.charAt(i)))
                    end = i;
    
                if(end != -1 && Character.isSpaceChar(s.charAt(i))) {
                    begin = i;
                    break;
                }
            }
    
            return end-begin;
        }
    }

  • 1
    D

    After you got the last non-space character, why did you start from the beginning of the string to find the last word, instead of going from there backward, in that way, the first word is the last word, right?


  • 0
    J

    Very nice indeed!


  • 0

    The idea of my solution is:
    memorize two words lengths: current word length (new ) and last word length (old).
    iterate through the string, if current char isn't ' ', then new length + 1.
    whenever encounter a ' '. set old word length = new (if new is not 0,i.e.two spaces in a row),reset new.
    at the end return new if new is not 0 (string not end with spaces).otherwise return old (last valid word )

    class Solution {
    public:
        int lengthOfLastWord(const char *s) {
            int o=0,n=0; // o for old, n for new.
            for (int i = 0; s[i] != 0; ++i)
            {
                if(s[i]!=' ')
                    n++;
                else{
                    o =(n)? n:o;
                    n = 0;
                }
            }
            return (n)? n:o;
        }
    };

  • 0
    M

    I have a similar solution like yours, but your code is much neater than my one.

    int lengthOfLastWord(const char *s) {
        int n;
        int q, cnt;
        for (cnt = 0, q = 0; s[q] != '\0'; q++) {
            if (s[q] != ' ')
                cnt++;
            else if (s[q+1] != ' ' && s[q+1] != '\0')
                cnt = 0;
        }
        
        return cnt;
    }
    

    The key point is we always count the length of a NEW word. Just figure out when a new word start and clean that counter. :)


  • 0
    S

    This solution is really intelligent and yet simple. I still believe there is both advantage and disadvantage. If the input string is long (let's say around 100 characters) and a 5 character word is at the end, then I think this solution will take more time as it will execute more operations than a solution that traverses from end. The reason I say that is because with this solution, it has to execute at least ~400 operations by the time it reaches at the last word. Where as if we traverse from end, then the only overhead is to count the input string length, which would be around ~200 operations "while (s[length] != '\0') length++;"
    I might be wrong, but would like to know your comments.


  • 1
    A

    I agree with your opinion, but your answer will not defend test cases with strings with white spaces at the end, like "word words " (caused me many WAs with Leetcode), which makes storing a temporary length useful.

    int lengthOfLastWord(const char *s) {
        int len = 0, lastlen = 0, i = 0;
        while (*s) {
            if (*s++ ==' ') len = 0; 
            else lastlen = ++len;
        }
        return lastlen;
    }

  • 0
    S

    Hey Alfred,
    This is mine that was accepted. This should take care of the test case that you are talking about.

    int lengthOfLastWord(const char *s) {
    int length = -1;
    while (s[++length] != NULL) { ; }
    for (int i = length - 1; i >= 0; i--) {
    if (s[i] != ' ') {
    int marker = i;
    while (--i >= 0 && s[i] != ' ') { ; }
    return marker - i;
    }
    }
    return 0;
    }


  • 0
    S

    Oops... how do I paste a code snippet in comment. Seems like it removes the new line and extra spaces. Sorry ... I'm new to leetcode.


  • 0
    S
    This post is deleted!

  • -1
    L

    Don't need to change len, just break the loop.

    class Solution:
    # @param s, a string
    # @return an integer
    def lengthOfLastWord(self, s=""):
        res=0;
        for i in range(len(s)-1,-1,-1):
            if(s[i].isalpha()):
                res+=1;
            elif(res!=0):
                break;
        return res;

  • 0
    L

    From right to left scan, then you code will more simply.

    See my code below.


  • 0
    C

    Count from the end of the string

    class Solution {
    public:
        int lengthOfLastWord(const char *s) {
            while(*s) s++;
            s--;
            while(*s == ' ') s--;
            int len = 0;
        	while (*s) {
        		if (*s == ' ') {
        			break;
        		}
        		else if (*s-- != ' ') len++;
        	}
        	return len;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.