The title

LeetCode 58, the last word length association type: string

You are given a string S, consisting of several words separated by Spaces. Returns the length of the last word in the string. If the last word does not exist, return 0. A word is the largest substring that consists only of letters and does not contain any space characters. Example 1: Input: s = "Hello World" Output: 5 Example 2: Input: s = "" Output: 0 Warning: 1 <= s.length <= 104 s Contains only letters and SpacesCopy the code

Time to solve the problem.

class Solution {
    public int lengthOfLastWord(String s) {
       
       
       
    }
}

Copy the code

The method input parameters are given above to complete the answer.

Subject analysis

  1. After seeing this problem, I don’t know what you think, anyway, my first thought is split, probably hopeless…
  2. Another way to think about it is to subtract the position of the last ‘ ‘from the total length to get the final length

Answers to analysis

This article only analysis I do the idea, only for reference, to understand a solution to the idea, other kinds of ideas to do the problem please access the Internet. The second way to solve the problem is to use the length subtraction directly, which is faster.

Answer successful: Execution time :1 ms, beating 38.61% of Java users memory consumption :36.8 MB, beating 48.22% of Java users

Class Solution {public int lengthOfLastWord(String s) {// lengthOfLastWord(String s) [] s1 = s.spit (" "); If (s1.length > 0) {return s1[s1.length - 1].length(); } else { return 0; }}}Copy the code

Answer successful: Execution time :0 ms, beat 100.00% Java user memory consumption :37.1 MB, beat 13.09% Java user

Class Solution {public int lengthOfLastWord(String s) {// lengthOfLastWord(String s) {s= s.rim (); Return s.length()-1 -s.lastIndexof (" "); }}Copy the code