mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
add: leetcode 0058 solution
This commit is contained in:
16
leetcode/0058.Length-of-Last-Word/58.Length of Last Word.go
Normal file
16
leetcode/0058.Length-of-Last-Word/58.Length of Last Word.go
Normal file
@ -0,0 +1,16 @@
|
||||
package leetcode
|
||||
|
||||
func lengthOfLastWord(s string) int {
|
||||
last := len(s) - 1
|
||||
for last >= 0 && s[last] == ' ' {
|
||||
last--
|
||||
}
|
||||
if last < 0 {
|
||||
return 0
|
||||
}
|
||||
first := last
|
||||
for first >= 0 && s[first] != ' ' {
|
||||
first--
|
||||
}
|
||||
return last - first
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question58 struct {
|
||||
para58
|
||||
ans58
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
type para58 struct {
|
||||
s string
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans58 struct {
|
||||
ans int
|
||||
}
|
||||
|
||||
func Test_Problem58(t *testing.T) {
|
||||
|
||||
qs := []question58{
|
||||
|
||||
{
|
||||
para58{"Hello World"},
|
||||
ans58{5},
|
||||
},
|
||||
|
||||
{
|
||||
para58{" fly me to the moon "},
|
||||
ans58{4},
|
||||
},
|
||||
|
||||
{
|
||||
para58{"luffy is still joyboy"},
|
||||
ans58{6},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 58------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans58, q.para58
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, lengthOfLastWord(p.s))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
41
leetcode/0058.Length-of-Last-Word/README.md
Normal file
41
leetcode/0058.Length-of-Last-Word/README.md
Normal file
@ -0,0 +1,41 @@
|
||||
# [58. Length of Last Word](https://leetcode-cn.com/problems/length-of-last-word/)
|
||||
|
||||
## 题目
|
||||
|
||||
Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
|
||||
|
||||
A word is a maximal substring consisting of non-space characters only.
|
||||
|
||||
Example 1:
|
||||
|
||||
```
|
||||
Input: s = "Hello World"
|
||||
Output: 5
|
||||
Explanation: The last word is "World" with length 5.
|
||||
```
|
||||
|
||||
Example 2:
|
||||
|
||||
```
|
||||
Input: s = " fly me to the moon "
|
||||
Output: 4
|
||||
Explanation: The last word is "moon" with length 4.
|
||||
```
|
||||
|
||||
Example 3:
|
||||
|
||||
```
|
||||
Input: s = "luffy is still joyboy"
|
||||
Output: 6
|
||||
Explanation: The last word is "joyboy" with length 6.
|
||||
```
|
||||
|
||||
## 题目大意
|
||||
|
||||
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。
|
||||
|
||||
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 先从后过滤掉空格找到单词尾部,再从尾部向前遍历,找到单词头部,最后两者相减,即为单词的长度
|
Reference in New Issue
Block a user