卖萌的弱渣

I am stupid, I am hungry.

Length of Last Word

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.

Note:

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

Example:

Given s = “Hello World”, return 5.

Solution

  • Java
(Length-of-Last-Word.java) download
1
2
3
4
5
6
7
8
9
10
public class Solution {
    public int lengthOfLastWord(String s) {
        if (s.length()==0)
            return 0;
        // 去掉首尾空格
        s = s.trim();
        int lastIndex = s.lastIndexOf(' ')+1;
        return s.length()-lastIndex;
    }
}
  • Python
(Length-of-Last-Word.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """

        if not s:
            return 0
        strs = s.split()
        # " "
        if len(strs) == 0:
            return 0
        return len(strs[-1])