1. The subject

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:

Enter: s = “Hello World”

Output: 5

Example 2:

Enter: s = “fly me to the moon”

Output: 4

Example 3:

Enter: s = “Luffy is still joyboy”

Output: 6

 

Tip:

  • 1 <= s.length <= 104
  • The s consists of only letters and Spaces
  • There is at least one word in s

2. The answer

Idea 1

Reverse order loop array

If not a space, the last word increments the current character;

If it is a space, it checks whether the last word has a value. If it has a value, it jumps out of the loop and returns the length of the last word. If it has no value, it ignores the space and continues

public int lengthOfLastWord(String s) {
    StringBuilder sb = new StringBuilder();

    for (int i = s.length() - 1; i > 0; i--) {
        if(s.charAt(i) ! =' ') {
            sb.append(s.charAt(i));
            continue;
        }

        if (sb.length() > 0) {
            break; }}return sb.length();
}
Copy the code

Time complexity

I’m using a layer 1 loop, so O(n)

Spatial complexity

Constant O (1)

Submit the results

The StringBuilder is used to store the string, but the StringBuilder is not required to return the string, so we can use int to record the string length

public int lengthOfLastWord(String s) {
    int length = 0;

    for (int i = s.length() - 1; i >= 0; i--) {
        if(s.charAt(i) ! =' ') {
            length++;
            continue;
        }

        if (length > 0) {
            break; }}return length;
}
Copy the code

Time complexity

I’m using a layer 1 loop, so O(n)

Spatial complexity

Constant O (1)

Submit the results