58 Length of last word

1. Problem description:

Given a string s containing only uppercase and lowercase letters and spaces '', return the length of its last word. If the string scrolls from left to right, the last word is the last word that appears.

If the last word does not exist, please return 0.

Note: A word refers to the largest substring consisting of letters only and not containing any space characters.

Example:

Input: "Hello World"
Output: 5

Source: LeetCode
link: https://leetcode-cn.com/problems/length-of-last-word

2. Thinking analysis:

① In fact, the idea is relatively simple. According to the title, you can know that there are only uppercase and lowercase letters and spaces in the string, so you can directly use the java api to solve it. In the java, you can use the split method to split the string. Here you can use spaces to split , The length of the last element is the result

② You need to pay attention to the special situation of the input string, just make a simple judgment

3. The code is as follows:

Directly written:

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

The code found in the solution to the collar buckle is very good. It is only able to start looking forward after the string, first removing the space, and then looking for the last word. The code is as follows:

class Solution {
    public int lengthOfLastWord(String s) {
        int end = s.length() - 1;
        while(end >= 0 && s.charAt(end) == ' ') end--;
        if(end < 0) return 0;
        int start = end;
        while(start >= 0 && s.charAt(start) != ' ') start--;
        return end - start;
    }
}

 

Published 569 original articles · Like 153 · Visits 590,000+

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/105303559