File tree Expand file tree Collapse file tree 3 files changed +107
-0
lines changed
leetcode/0058.Length-of-Last-Word Expand file tree Collapse file tree 3 files changed +107
-0
lines changed Original file line number Diff line number Diff line change 1+ package leetcode
2+
3+ func lengthOfLastWord (s string ) int {
4+ last := len (s ) - 1
5+ for last >= 0 && s [last ] == ' ' {
6+ last --
7+ }
8+ if last < 0 {
9+ return 0
10+ }
11+ first := last
12+ for first >= 0 && s [first ] != ' ' {
13+ first --
14+ }
15+ return last - first
16+ }
Original file line number Diff line number Diff line change 1+ package leetcode
2+
3+ import (
4+ "fmt"
5+ "testing"
6+ )
7+
8+ type question58 struct {
9+ para58
10+ ans58
11+ }
12+
13+ // para 是参数
14+ type para58 struct {
15+ s string
16+ }
17+
18+ // ans 是答案
19+ type ans58 struct {
20+ ans int
21+ }
22+
23+ func Test_Problem58 (t * testing.T ) {
24+
25+ qs := []question58 {
26+
27+ {
28+ para58 {"Hello World" },
29+ ans58 {5 },
30+ },
31+
32+ {
33+ para58 {" fly me to the moon " },
34+ ans58 {4 },
35+ },
36+
37+ {
38+ para58 {"luffy is still joyboy" },
39+ ans58 {6 },
40+ },
41+ }
42+
43+ fmt .Printf ("------------------------Leetcode Problem 58------------------------\n " )
44+
45+ for _ , q := range qs {
46+ _ , p := q .ans58 , q .para58
47+ fmt .Printf ("【input】:%v 【output】:%v\n " , p , lengthOfLastWord (p .s ))
48+ }
49+ fmt .Printf ("\n \n \n " )
50+ }
Original file line number Diff line number Diff line change 1+ # [ 58. Length of Last Word] ( https://leetcode-cn.com/problems/length-of-last-word/ )
2+
3+ ## 题目
4+
5+ Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
6+
7+ A word is a maximal substring consisting of non-space characters only.
8+
9+ Example 1:
10+
11+ ```
12+ Input: s = "Hello World"
13+ Output: 5
14+ Explanation: The last word is "World" with length 5.
15+ ```
16+
17+ Example 2:
18+
19+ ```
20+ Input: s = " fly me to the moon "
21+ Output: 4
22+ Explanation: The last word is "moon" with length 4.
23+ ```
24+
25+ Example 3:
26+
27+ ```
28+ Input: s = "luffy is still joyboy"
29+ Output: 6
30+ Explanation: The last word is "joyboy" with length 6.
31+ ```
32+
33+ ## 题目大意
34+
35+ 给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。
36+
37+ 单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
38+
39+ ## 解题思路
40+
41+ - 先从后过滤掉空格找到单词尾部,再从尾部向前遍历,找到单词头部,最后两者相减,即为单词的长度
You can’t perform that action at this time.
0 commit comments