Without using trim/indexOf functions


  • 0
    E
        public int lengthOfLastWord(String s) {
            int length = 0;
            int i = s.length()-1 ;
            while(i>=0){
                if(s.charAt(i) == ' ' && i == s.length()-1){
                   while( i >= 0 && s.charAt(i) == ' ') i--;
                }
                while(i >= 0 && s.charAt(i) != ' '){
                    length++;
                    i--;
                }
                break;
            }
            return length;
        }
    }
    

Log in to reply
 

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