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