Java solution with simple loop and a flag


  • 0
    S

    A simple solution which does not use any 'trim' or other library methods

    public int lengthOfLastWord(String s) {
            
            char[] c = s.toCharArray();
            boolean noWord=true;
            int count=0;
            for(int i=c.length-1; i>=0 ; i--){
                if(c[i]!= ' '){
                    noWord=false;
                    count++;
                }else if(c[i]== ' ' && !noWord){
                    break;
                }
            }
            
            if(noWord) return 0;
            return count;
            
        }
    

Log in to reply
 

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