Length of Last Word go语言实现

2018-09-22  本文已影响0人  fjxCode

Length of Last Word

题目描述

Given a string s consists of upper/lower-case alphabets and empty space characters' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example, 
Given s ="Hello World",
return5.

思路:

解:

package main

import (
    "fmt"
    "strings"
)

func lengthOfLastWord(s string) int {
    if len(s) == 0 {
        return 0
    }
    s = strings.TrimRight(s," ")

    sByte := []byte(s)
    res := 0
    i := len(sByte)-1
    for ;i>=0 ;i--  {
        if sByte[i] == ' ' {
            break
        }
        res++
    }
    return res
}

func main()  {
    s  := " "
    res := lengthOfLastWord(s)
    fmt.Print(res)

}
上一篇下一篇

猜你喜欢

热点阅读