My simple Java Solution

  • 0

    If there is any way to refine it, please reply to me. I really appreciate it.

    public int lengthOfLastWord(String s) {
            boolean find = false;
            int length =0;
            int i =0,j =0;
                if(s.charAt(i)!=' '&&!find){
                    j = i;
                    find = true;
                if(s.charAt(i)==' '&&find){
                    length = i -j;
                    find = false;
                return i -j;
                return length;

  • 0

    I slightly modified the usage of flags and started from the end of the string as we need the last word length. Here is my code

    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]!= ' '){
                }else if(c[i]== ' ' && !noWord){
            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.