Monday, July 21, 2014

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.

首先找到第一不是空格的地方,然后找第二个。
如果能改变string,可以用trim预处理string,可以省去第一步。
public class Solution {
    //Time: O(n)
    public int lengthOfLastWord(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        int right = s.length() - 1;
        for (; right >= 0; right--) {
            if (s.charAt(right) != ' ') {
                break;
            }
        }
        if (right < 0) {
            return 0;
        }
        int left = right;
        for (; left >= 0; left--) {
            if (s.charAt(left) == ' ') {
                break;
            }
        }
        return right - left;
    }
}

No comments:

Post a Comment