Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does LeetCode find the length of the last word?

Shulou Source: shulou.com Published: 2022-06-01 13:03:40 11月14日 Update

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!

Tags: Words characters length strings letters examples spaces articles problem solutions maximum size done that is general ideas more knowledge programs industries information Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Tech Info MariaDB Huawei Xiaomi