Java 5ms Easy to Understand Solution


  • 0
    public class Solution {
        public int lengthOfLastWord(String s) {
            if(s.length() == 0) return 0;
            int end = 0;
    
            for(int i = s.length() - 1; i >= 0; i--){
                if((i == s.length() - 1 || s.charAt(i+1) == ' ') && s.charAt(i) != ' '){
                    end = I;//record end index
                }
                if((i == 0 || s.charAt(i-1) == ' ') && s.charAt(i) != ' '){
                    return end - i + 1;//start index is i for now
                }
            }
            return 0;
        }
    }
    
    

Log in to reply
 

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