Java Solution without Lib Help


  • 0
    J
    public int lengthOfLastWord(String s) {
        int lastLen = 0;
        int len = 0;
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == ' '){
                len = 0;
            }else{
                len++;
                lastLen = len;
            }
        }
        return lastLen;
    }

  • 0
    J

    Only uses one loop.

    The var len stores the current length of the word which will be 0 when current char is a space .The var lastLen stores the length before the current space in case the last char is a space where you can only get len = 0


Log in to reply
 

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