A single line of Code in Java


  • 46
    L
    public int lengthOfLastWord(String s) {
        return s.trim().length()-s.trim().lastIndexOf(" ")-1;
    }

  • 41
    S

    Your solution is very practical, but note that what your interviewer wants to hear more about is probably how you would deal with this problem on a lower level, without the help of those standard library functions. If you give an answer like this, then your interviewer will probably ask you to implement two more functions: trim and lastIndexOf.


  • 1
    L

    Understand and agree, thank you. Actually, I just use this solution to compare the time cost with the lower level solution. Then, I think I should give out my lower level solution as well.


  • 29
    L

    This one single line solution is just used to compare the time cost with the solution below:
    (Time cost: 348ms vs. 344ms, almost the same)

    public int lengthOfLastWord(String s) {
        int len=s.length(), lastLength=0;
        
        while(len > 0 && s.charAt(len-1)==' '){
            len--;
        }
        
        while(len > 0 && s.charAt(len-1)!=' '){
            lastLength++;
            len--;
        }
        
        return lastLength;
    }
    

    While, with the same algorithm in C++, it's 8ms:

    int lengthOfLastWord(const char *s) {
        int len=strlen(s), lastLength=0;
        
        while(len > 0 && s[len-1]==' '){
            len--;
        }
        
        while(len > 0 && s[len-1]!=' '){
            lastLength++;
            len--;
        }
        
        return lastLength;
    }

  • 0
    W

    I like your idea. Comparing to my version, it can't be more concise, because my algorithm have a lot of if-else. Thx for your sharing.


  • 0
    R

    This is a neat solution. A Java related question, you have called trim() twice. I doubt if JVM would optimize this and trim will be called just once. Would saving s.trim() in a variable would be somewhat more efficient ? (Though, I know this will make the solution > 1 line )


  • 0
    K
    public int lengthOfLastWord(String s) {
           String s1=s.trim();
           int x=s1.lastIndexOf(" ");
           if(x==-1)
           return s1.length();
           else
           return s1.substring(x,s1.length()-1).length();
    }
    

    I guess this will be more efficient with a single usage of trim(). However even after optimizing it, it takes 332 ms which seems quite large.


  • 1
    M

    Something about c-strings lol


  • 2
    H

    One line solution too.

    return (s.split(" ").length == 0) ? 0 : s.split(" ")[s.split(" ").length-1].length();


  • 0

    Nice. This is how it works, and what it should be, in real life. LOL


  • 0
    D

    What a fucking done!


  • 0

    @lvlolitte It seems your solution is not as "not so efficient" as it looks, I mean I cannot figure out why your solution is so slow, 344 ms. I used split() only takes 8ms in Java.

    My understanding in Java is not so deep. Can you explain it for me? Thanks!

    public int lengthOfLastWord(String s) {
            if (s.length() == 0 || s == null) return 0;
            String[] str = s.split(" ");
            if (str.length == 0 || str == null) return 0;
            return str[str.length - 1].length();
        }
    

  • 0
    S

    @hu26 When I saw the description in top solutions about one line, this is the one I tried and got accepted. :)


  • 1
    L

    I have a simple algorithm:

    it scans the string backwards from the tail. At first, the length of the last word is set to be zero. If a whitespace is found, we check if it is a trailing whitespace. If it is not a trailing whitespace (i.e. the length is not zero any more), we return the length. If it is a trailing whitespace (i.e. the length is zero), we continue the scan.

    public class Solution {
        public int lengthOfLastWord(String s) {
        int len=0;
        for(int i=s.length()-1;i>=0;i--){
            if(s.charAt(i)==' '){
                //If it is not a trailing space, return the length.
               if(len!=0) return len;
            }else{
               len++;
            }
        }
        return len;
        }
    

  • 0
    G

    @lvlolitte Absolutely,it's a easy question,but I just wonder why the AC rate is so low,
    java:

    public class Solution {
        public int lengthOfLastWord(String s) {
            String[] ss=s.split(" +");
      		int sLen=ss.length;
            return sLen==0?0:ss[sLen-1].length();
        }
    }
    

    python

    class Solution(object):
        def lengthOfLastWord(self, s):
            ss=s.split()
            return len(ss[-1]) if ss!=[] else 0
    

  • 0
    D

    I had the similar solution as @lvlolitte at the first place. But after inspired by @stellari, I removed all trim() and lastIndexOf() methods. And my new code produced surprisingly not too bad result (though a bit long for an easy problem):

    public class Solution {
        public int lengthOfLastWord(String s) {
            int lastIndex = -1;
            // find the last non-space character
            for (int i=s.length()-1; i>-1; i--){
                if (s.charAt(i) != ' '){
                    lastIndex = i;
                    break;
                }
            }
            
            if (lastIndex > -1){
                // if there is leading space, this part handles it
                for (int i=lastIndex; i>-1; i--)    if (s.charAt(i)==' ')   return (lastIndex-i);
            }
            
            return lastIndex==-1? 0: lastIndex+1;
        }
    }
    

  • 0
    S

    @stellari unfortunately this is not Java question.
    Yes, it can be done using char array, like below. But this is not natural way for string manipulation in Java, and to be honest in that case performance pros are minimal, but code becomes too complicated to understanding.

    	public int lengthOfLastWord(String s) {
    		char[] ca = s.toCharArray();
    		
    		int index = ca.length - 1;
    		
    		while (index >= 0 && ca[index] == ' ') index--;
    		if (index == -1) return 0;
    
    		int end = index;
    		index--;
    
    		while (index >= 0 && ca[index] != ' ') index--;
    
    		return end - index;
    	}
    
    

Log in to reply
 

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