This is the 18th day of my participation in the August Challenge


Related articles

LeetCode brush questions summary: LeetCode brush questions

1. Title Description


Number of happiness

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.

Start with simple questions to brush, exercise their thinking ability, for the interview preparation ~

Second, train of thought analysis


  • Look at the examples in the title, let’s clarify the idea ~

  • Example 1:

    Input: s = "Hello World" Output: 5Copy the code
  • Example 2:

    Input: s = "fly me to the moon" output: 4Copy the code
  • Example 3:

  • Input: s = "Luffy is still joyboy" Output: 6Copy the code
  • They want us to find the last string, so how do we find the last string?
  • Because strings passed in are separated by Spaces, they are traceable.
  • You can use split to split an array of characters based on whitespace, and the last of the array is the last string.

AC code


  • String splitting method:

    Class Solution {public int lengthOfLastWord(String s) {// Split it into String array String[] arr = s.split(" "); Return arr[arr.length-1].length(); return arr[arr.length-1].length(); }}Copy the code
    • The solution is crude and unaesthetic.
  • Reverse cycle solution method:

    class Solution { public int lengthOfLastWord(String s) { int count = 0; S = s.rim (); for (int i=s.length()-1; i>=0; If (s.char (I) == "){break; if(s.char (I) == "){break; }else { count++; } } return count; }}Copy the code
    • As can be seen from the results, significantly higher than the original efficiency!
    • This idea is loop, loop yyds!!

Four,

  • Thousands of ideas to solve the problem, whether this method is good, or whimsical solution, can solve is a good way! White cat black cat can catch mice cat is a good cat!
  • There are thousands of solutions to this simple problem, choose the most suitable for you! Below list the solution of other great god, provide reference!
  • Click jump: Draw solution algorithm
  • In fact, I really like my first solution, although the efficiency is a little under, but at least the perfect use of Java method ah! Live learning and use! Ha ha

I see a long way to go, I’m sure I’ll keep searching ~ ** If you think I’m a good blogger! Writing is not easy, please like, follow, comment and give encouragement to the blogger ~ Hahah