diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index 78e8827..438a46b 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -2540,3 +2540,43 @@ func countSubarrays(nums []int, minK int, maxK int) int64 { ### 总结 本次解题代码的运行速度超过了100%的提交, 因此不再看他人的题解了, 同时庆祝一下自己拿到了3月份的奖章, 证明这个月每天都在坚持. 下个月希望能继续坚持下去. + +## day34 2024-04-01 + +### 58. Length of Last Word + +Given a string s consisting of words and spaces, return the length of the last word in the string. + +A word is a maximal substring consisting of non-space characters only. +![04010SzI491D9VfR](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/04010SzI491D9VfR.png) + +### 题解 + +本题是一道简单题, 直接从头开始遍历, 遇到空格结束当前单词计数, 再遇到新字符时重新计数, 直到遍历完整个字符串即可. + +### 代码 + +```go +func lengthOfLastWord(s string) int { + length := 0 + flag := false + for _, value := range s{ + if value == ' ' { + flag = true + } + if value != ' ' { + if flag{ + length = 1 + flag = false + }else{ + length++ + } + } + } + return length +} +``` + +### 总结 + +前面的题解大多用了go strings库中的函数来按空格分割字符串, 再返回最后一个分割出来的字符串长度. 一般实际应用中, 使用官方库是第一选择, 因为官方库大多对这些操作做了大量优化, 效率会高得多.