add: leetcode 0058 solution

This commit is contained in:
tphyhFighting
2021-09-15 17:04:01 +08:00
parent 29880358f0
commit 3c11d93a29
3 changed files with 107 additions and 0 deletions

View 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
}

View File

@ -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")
}

View 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由若干单词组成单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
## 解题思路
- 先从后过滤掉空格找到单词尾部,再从尾部向前遍历,找到单词头部,最后两者相减,即为单词的长度