Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3b48480

Browse files
committed
commit solution 58
1 parent 5af5070 commit 3b48480

File tree

3 files changed

+52
-6
lines changed

3 files changed

+52
-6
lines changed

‎solution/1-99/0058.length-of-last-word/README.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# [58. 最后一个单词的长度](https://leetcode-cn.com/problems/length-of-last-word)
22

33
### 题目描述
4-
<!-- 这里写题目描述 -->
4+
55
<p>给定一个仅包含大小写字母和空格&nbsp;<code>&#39; &#39;</code>&nbsp;的字符串 <code>s</code>,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。</p>
66

77
<p>如果不存在最后一个单词,请返回 0&nbsp;。</p>
@@ -17,18 +17,21 @@
1717
</pre>
1818

1919

20-
2120
### 解题思路
2221

2322

2423
### 具体解法
2524

26-
<!-- tabs:start -->
27-
2825
#### **Golang**
2926
```go
30-
27+
func lengthOfLastWord(s string) int {
28+
if len(s) == 0 {
29+
return 0
30+
}
31+
s = strings.TrimSpace(s)
32+
sArr := strings.Split(s, " ")
33+
return len(sArr[len(sArr)-1])
34+
}
3135
```
3236

33-
<!-- tabs:end -->
3437

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package leetcode
2+
3+
import "strings"
4+
5+
/*
6+
* @lc app=leetcode.cn id=58 lang=golang
7+
*
8+
* [58] 最后一个单词的长度
9+
*/
10+
11+
// @lc code=start
12+
func lengthOfLastWord(s string) int {
13+
if len(s) == 0 {
14+
return 0
15+
}
16+
s = strings.TrimSpace(s)
17+
sArr := strings.Split(s, " ")
18+
return len(sArr[len(sArr)-1])
19+
}
20+
21+
// @lc code=end
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package leetcode
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestLengthOfLastWord(t *testing.T) {
8+
var ret int
9+
var s string
10+
11+
s = ""
12+
ret = 0
13+
if ret != lengthOfLastWord(s) {
14+
t.Fatalf("case fails %v\n", ret)
15+
}
16+
17+
s = "Hello World"
18+
ret = 5
19+
if ret != lengthOfLastWord(s) {
20+
t.Fatalf("case fails %v\n", ret)
21+
}
22+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /