美文网首页
Length of Last Word go语言实现

Length of Last Word go语言实现

作者: fjxCode | 来源:发表于2018-09-22 15:29 被阅读0次

    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)
    
    }
    

    相关文章

      网友评论

          本文标题:Length of Last Word go语言实现

          本文链接:https://www.haomeiwen.com/subject/ynhxoftx.html