Golang, 3ms solution


  • 0
    func lengthOfLastWord(s string) int {
        w, i := []int32{}, 0
        for _, b := range s {
            if b == 32 { // space decimal code
                w = []int32{}
            } else {
                w = append(w, b)
                i = len(w)
            }
        }
        return i
    }
    

  • 0

    Nice to see Go, though no need to store the word's characters:

    func lengthOfLastWord(s string) int {
        curr, last := 0, 0
        for _, b := range s {
            if b == 32 { // space decimal code
                curr = 0
            } else {
                curr++
                last = curr
            }
        }
        return last
    }
    

  • 0

    ahh good catch, thanks @StefanPochmann


Log in to reply
 

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