Simple Solution in One Loop


#1
public class Solution {
    // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY
    public int lengthOfLastWord(final String A) {
        if(A.length() == 0) return 0;
        int l = 0;
        boolean isSpace = true;
        for(int i = A.length()-1; i > -1; i--) {
            if(A.charAt(i) == ' ' && isSpace == true) continue;
            if(A.charAt(i) == ' ' && isSpace == false) break;
            else {
                isSpace = false;
                l++;
            }
        }
        return l;
    }
}