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.

For example,
Given s = “Hello World”,
return 5.
这道题比较简单,直接从后面开始扫,如果扫到letter,记下start, 再扫到非letter,记下end,然后相减即可,注意处理没有扫到letter和扫到0还是字母的情况。

public class Solution {
    public int lengthOfLastWord(String s) {
        boolean found = false;
        int start = 0, end = 0; // start and end
        for (int i = s.length() - 1; i >= 0; i--)
        {
            if (Character.isLetter(s.charAt(i)))
            {
                start = i;
                found = true;
                break;
            }
        }
        if (!found)
            return 0;
        for (end = start-1; end >= 0; end--)
        {
            if(!Character.isLetter(s.charAt(end)))
                return start - end;
            
        }
        return start + 1;
    }
}

Use the trim function to make things simple, trim the string first to get rid of the trailing spaces.

public class Solution {
    public int lengthOfLastWord(String s) {
        s = s.trim(); // remove the head and trailing spaces
        if (s.length() == 0)
            return 0;
        int len = 0;
        for (int i = s.length()-1; i >= 0; i--) {
            if (Character.isLetter(s.charAt(i)))
                len++;
            else
                break;
        }
        return len;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s