Java 5ms solution


  • 0
    A
        public int lengthOfLastWord(String s) {
             if(s.length()==0){
                return 0;
             }
                int ans = 0;
                int i = s.length()-1;
                char current = s.charAt(i);
                
                while(current == ' '){
                i--;    
                if(i<0){
                    return 0;
                }
                current = s.charAt(i);
                }
                
                while(current != ' '){
                    ans++;
                    i--;
                    if(i<0){
                    return ans;
                }
                    current = s.charAt(i);
                }
                return ans;
            }
        }

Log in to reply
 

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