Neat Java Solution.. Does not use split() function


  • 0
    M
    public int lengthOfLastWord(String s) {
            
            int len = 0;
            boolean isLastSpace = true;
            
            if (s == null || s.trim().equals("")) {
                return len;
            }
            
            for (int i=s.length() - 1; i >= 0; i--) {
                
                if (s.charAt(i) == ' ' && isLastSpace) {
                    while (s.charAt(i) == ' ') {
                        i--;
                    }
                }
                
                if (isLastSpace) isLastSpace = !isLastSpace;
                
                if (s.charAt(i) == ' ') {
                    return len;
                }
                len++;
            }
            return len;
        }
    

Log in to reply
 

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