Fast Code Of Go Go Go


  • 0

    1.You should remove all space char of tail of the string.
    2.Well, you count the last length of the word.It's better to count the position of the word from the tail of the string.
    3.That's all.

    func lengthOfLastWord(s string) int {
    	pos := len(s) - 1
    	for ; pos >= 0; pos-- {
    		if !unicode.IsSpace(rune(s[pos])) {
    			break
    		}
    	}
    	s = s[:pos + 1]
    	if len(s) == 0 {
    		return 0
    	}
    
    	for ; pos >= 0; pos-- {
    		if unicode.IsSpace(rune(s[pos])) {
    			break
    		}
    	}
    	return len(s[pos+1:])
    }
    

Log in to reply
 

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