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;
            for(;i<s.length();i++){
                if(s.charAt(i)!=' '&&!find){
                    j = i;
                    find = true;
                }
                if(s.charAt(i)==' '&&find){
                    length = i -j;
                    find = false;
                }
            }
            
            if(find){
                return i -j;
            }else{
                return length;
            }
        }
    

  • 0
    S

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