Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.
Spring Recruit punch card day 22 chapter 30.
Study like the seedlings of spring, see its increase, day has a director; Drop out of school such as a whetstone, see its loss, loss.
There are so many activities in digging gold. This month, I decided to use GO to brush the questions every day, on the one hand, to improve the algorithm level, on the other hand, to settle the learning of GO language.
Let’s GO!
Topic describes
You are given a string s, consisting of several words separated by space characters. Returns the length of the last word in the string.
A word is the largest substring that consists only of letters and does not contain any space characters.
The sample
Example 1:
Enter: s = “Hello World”
Output: 5
Explanation: The last word is “World” and is 5 in length.
Example 2:
Enter: s = “fly me to the moon”
Output: 4
Explanation: The last word is “moon” and is 4 in length.
Example 3:
Enter: s = “Luffy is still joyboy”
Output: 6
Explanation: The last word is “joyboy” of length 6.
Tip:
1 <= s.length <=
The s consists of only letters and Spaces
There is at least one word in s
Subject analysis
- After reading the description, the first reaction is to split the string into arrays based on Spaces
- Getting the length of the last word in the array is the length we need
- But the above method is not optimal, since we want to find the length of the last word, we can use it
Reverse traversal
The thinking of
Thinking on
- There must be at least one word in the string.
- First find the last letter in the string, which is the last letter of the last word.
- Continue traversing the string in reverse, starting with the last letter, until a space is encountered or the beginning of the string is reached.
- Each letter iterated is the letter in the last word, so the number of letters iterated is the length of the last word.
AC code
func lengthOfLastWord(s string) (ans int) {
// Get the maximum index position by traversing backwards
index := len(s) - 1
for s[index] == ' ' {
index--
}
// The inverted index is not running out and the value of the index is not an empty string
for index >= 0&& s[index] ! =' ' {
ans++
index--
}
return
}
Copy the code
The results
conclusion
Complexity analysis:
Time complexity: O(n), where n is the length of the string.
Space complexity: O(1).
sources
Source: LeetCode
Link: leetcode-cn.com/problems/le…
Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
The last
Thanks for reading and welcome to like, favorites,coin(attention)!!