Monday, March 4, 2013

[LeetCode] Length of Last Word

Thought:
Scan from the end, until we find the first nonspace character, then add result until we find the first space.

Code:
public class Solution {
    public int lengthOfLastWord(String s) {
        int len = s.length();
        int result = 0;
        while (len >= 1 && s.charAt(len - 1) == ' ') len--;
        while (len >= 1 && s.charAt(len - 1) != ' ') {
            len--;
            result++;
        }
        return result;
    }
}

No comments:

Post a Comment