Length of Last Word 422

Question

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Notice

A word is defined as a character sequence consists of non-space characters only.

Example

Given s = "Hello World", return 5.

Solution

方法一:可以直接对string去掉首尾的空格,然后根据空格分割字符串,取最后的元素即可。

方法二:从后往前遍历,忽略遇见第一个非空格字符之前的所有空格,在遇见第一个非空格字符之后再次遇见空格字符则break。

代码如下:

方法一:

public class Solution {
    /**
     * @param s A string
     * @return the length of last word
     */
    public int lengthOfLastWord(String s) {
        // Write your code here
        if(s == null || s.length() == 0){
            return 0;
        }

        String[] str = s.trim().split(" ");

        return str[str.length - 1].length();
    }
}

方法二:

public class Solution {
    /**
     * @param s A string
     * @return the length of last word
     */
    public int lengthOfLastWord(String s) {
        // Write your code here
        if(s == null || s.length() == 0){
            return 0;
        }

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

results matching ""

    No results matching ""