您的位置 首页 golang

Golang 刷题 Leetcode 58. Length of Last Word

题目: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.

给一个 字符串 ,返回最后一个单词的长度,单词之间用空格分割

思路

先用空格分割字符串,注意处理连续空格,直接计算最后一个即可

code

func lengthOfLastWord(s string) int {
arr := strings.Split(strings. Trim (s, " "), " ")
length := len(arr)
res := 0
for i := length - 1; i >= 0; i-- {
if arr[i] == " " {
 continue 
} else {
res = len(arr[i])
 break 
}
}
return res
}
 

更多内容请移步我的repo:

文章来源:智云一二三科技

文章标题:Golang 刷题 Leetcode 58. Length of Last Word

文章地址:https://www.zhihuclub.com/86270.shtml

关于作者: 智云科技

热门文章

网站地图