leetcode刷题笔记(Golang)--58. Length of Last Word

58. Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: “Hello World”
Output: 5

func lengthOfLastWord(s string) int {
	lg := len(s)
	l := 0
	r := lg - 1

	for r >= 0 && s[r] == ' ' {
		r--
	}
	for r >= 0 && s[r] != ' ' {
		r--
		l++
	}

	return l
}
发布了65 篇原创文章 · 获赞 0 · 访问量 372

猜你喜欢

转载自blog.csdn.net/weixin_44555304/article/details/104261957