“This is the 8th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

describe

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.

  • 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
  • Tip:
  • 1 <= s.length <= 104
  • sOnly English letters and Spaces' 'composition
  • sAt least one word exists in

parsing

A string, separated by Spaces, is the length of the string. The string must contain letters because at least one word exists in the string. First find the last letter in the string, which is the last letter of the last word.

Continue traversing the string in reverse, starting with the last letter, until a space is encountered or the beginning of the string is reached. Each letter iterated is the letter in the last word, so the number of letters iterated is the length of the last word.

Complexity:

  • Time complexity: O(n), where n is the length of the string. The string needs to be traversed backwards at most once.
  • Space complexity: O(1).

The sample

class Solution { public int lengthOfLastWord(String s) { if (s.length() == 0) { return 0; } int res = 0; // hasMetSpace: hasMetSpace: hasMetSpace: hasMetSpace: hasMetSpace: Boolean hasMetSpace = false, hasMetWord = false; for (int i = s.length() - 1; i >= 0; -- I) {if (s.char (I) == "&&hasmetWord") {// If (s.char (I) == "&&hasmetWord") {// If (s.char (I) == "&&hasmetWord") {// If (s.char (I) == "&&hasmetWord") {// If (s.char (I) == "&&hasmetWord") { } if (s.charAt(i) ! = "&&! HasMetSpace) {// If a valid character is encountered but no Spaces between words are encountered, // this character belongs to the last word hasMetWord = true; ++res; } } return res; }}Copy the code

Method 2:

class Solution {
    public int lengthOfLastWord(String s) {
        int l = s.length()-1;
        while(l>=0 && s.charAt(l) == ' '){
            l--;
        }
        int i = 0;
        while( l>=0 && s.charAt(l) != ' '){
            i++;
            l--;
        }
        return i;
    }
}
​
Copy the code

Running results:

Result: Yes

Execution time: 1 ms, beating 73.21% of all Java commits

Memory consumption: 37.1 MB, beating 87.2 percent of all Java commits