228ms Java Solution


  • 13

    1 - Use 2 loops. One to locate the last non-space character, one to count.

    public int lengthOfLastWord(String s) {
        //228ms
        int lenIndex = s.length()-1;
        int len = 0;
    
        /*can also use while here, resulting in 264ms
        while (lenIndex>=0 && s.charAt(lenIndex)==' ') lenIndex--;*/
        
        /*or use trim - 324ms
        s = s.trim();*/
    
        for (int i=lenIndex; i>=0 && s.charAt(i)==' '; i--) 
            lenIndex--;
        
        for (int i=lenIndex; i>=0 && s.charAt(i)!=' '; i--) 
            len++;
        return len;
    }
    

    2 - Use split

        //292ms
        String[] words = s.split(" ");
        if (words.length==0) return 0;
        else return words[words.length-1].length();
    

    3 - use lastIndexOf

        //308ms
        return s.trim().length() - s.trim().lastIndexOf(" ") - 1;

Log in to reply
 

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