[58] The length of the last word [LeetCode]

1. Topic description

You are given a string  sconsisting of several words separated by some space characters before and after them. Returns   the length of the last word in the string.

A word  is the largest substring consisting of only letters and not containing any space characters.

Example 1:

Input: s = "Hello World"
 Output: 5
 Explanation: The last word is "World" and has a length of 5.

Example 2:

Input: s = "fly me to the moon"
 Output: 4 
Explanation: The last word is "moon" and has a length of 4.

Example 3:

Input: s = "luffy is still joyboy"
 Output: 6
 Explanation: The last word is "joyboy" of length 6.

hint:

  • 1 <= s.length <= 104
  • s' ' Consists of  only English letters and spaces 
  • s at least one word exists in

2. Core code​​​​​​​

class Solution {
    public int lengthOfLastWord(String s) {
        String[] split = s.split(" ");
        return split[split.length - 1].length();
    }
}

3. Test code​​​​​​​

class Solution {
    public int lengthOfLastWord(String s) {
        String[] split = s.split(" ");
        return split[split.length - 1].length();
    }
}
// @solution-sync:end

class Main {

    public static void main(String[] args) {
        String s = "Hello World";

        int result = new Solution().lengthOfLastWord(s);
        System.out.println(result);
    }

}

Guess you like

Origin blog.csdn.net/qq_45037155/article/details/124356565