Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does LeetCode find the length of the last word?

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

The editor will share with you how LeetCode seeks the length of the last word. I hope you will get something after reading this article. Let's discuss it together.

First, the length of the last word 1, a brief description of the problem.

Given a string s that contains only uppercase and lowercase letters and spaces'', returns the length of its last word. If the string scrolls from left to right, the last word is the last word that appears.

If the last word does not exist, return 0.

Description: a word is the largest substring that consists of only letters and does not contain any space characters.

2. Example description example:

Enter: "Hello World"

Output: 5

3, the train of thought of solving the problem

The general operation of a string can be completed by processing each character according to the length of the string.

4, problem solving procedure

Public class LengthOfLastWordTest2 {

Public static void main (String [] args) {

String s = "Hello World"

Int lengthOfLastWord = lengthOfLastWord (s)

System.out.println ("lengthOfLastWord =" + lengthOfLastWord)

}

Public static int lengthOfLastWord (String s) {

If (s = = null | | s.length () = = 0) {

Return 0

}

Char [] toCharArray = s.toCharArray ()

Int length = toCharArray.length

Int count = 0

For (int I = length-1; I > = 0; iMury -) {

If (s.charAt (I)! =') {

Count++

} else if (count > 0) {

Return count

}

}

Return count

}

}

After reading this article, I believe you have a certain understanding of "how to find the length of the last word in LeetCode". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report