Search This Blog

Tuesday, December 18, 2012

LeetCode: Length of Last Word

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.

public class Solution {
    public int lengthOfLastWord(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(s==null) return 0;
        char[] c = s.toCharArray();
        
        int i=s.length()-1, j=i;
        while(i>=0){
            while(i>=0 && !isLetter(c[i])) i--;
            if(i>=0){
                j=i;
                while(j>=0 && isLetter(c[j])) j--;
                if(j<0 || c[j]==' ') return i-j;
                i=j;
                while(i>=0 && c[i]!=' ') i--;
            }
        }
        return 0;
    }
    
    public boolean isLetter(char c){
        if(c>='a' && c<='z' || c>='A' && c<='Z')
            return true;
        else
            return false;
    }
}

3 comments:

Anonymous said...

There is one line with bug:

while(i>=0 && i!=' ') i--;

it should be
while(i>=0 && c[i]!=' ') i--;

Xun said...

Yes, thanks for pointing it out.

Anonymous said...

public int lengthOfLastWord(String s) {
s = s.trim();
String [] res = s.split(" ");
return res[res.length-1].length();
}