[Leetcode 3] 58 Length of Last Word

Problem:

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.

 

Analysis:

Start from the last position of the given String. We not start counting until meet with a non-' ' character. Then we start count the occurace of no-' ' character until 1. meet with a ' ' or 2. reach the head of the string. Some special cases may be: S="", S="       ", S="ssssss"

The time complexity in worst case is O(n), the space complexity is O(n), n is the number of characters of the String

 

Code:

public class Solution {
    public int lengthOfLastWord(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if (s.equals("")) return 0;
        
        int p, len=0;
        
        for (p = s.length()-1; p>=0 && s.charAt(p)==' '; p--) ;
            
        for (len=0; p>=0 && s.charAt(p)!=' '; len++, p--) ;
        
        return len;
    }
}

 

Attention:

Judging whether S is an "", can't use S==null, because S is a reference which always isn't null, use S.equals("") or S.length()==0 to instead

Java String doesn't support [] operator, use charAt(int i) to instead

posted on 2013-04-06 13:52  freeneng  阅读(256)  评论(0编辑  收藏  举报

导航