Monthly Archives: January 2015

LeetCode OJ: Length of Last Word

Length of Last Word

Total Accepted: 29154 Total Submissions: 100944

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.

https://oj.leetcode.com/problems/length-of-last-word/

Solution: see the comment in the code , writed in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
public static int lengthOfLastWord(String s) {
    if(s.length() == 0) return 0; // input may be ""
 
    int result = -1;
 
    int skipEmpty = 0;
    // skip empty string at the end of input string s
    for(int i= s.length() - 1;i>=0;i--)
        {
            if(s.charAt(i) == ' ') continue;
            else {
                skipEmpty = i;
                break;
            }
        }
    //Start to Calculate
    for(int i= skipEmpty;i>=0;i--)
        {
            if(s.charAt(i) != ' ') continue;
            else {
                result = i;
                break;
            }
 
        }
 
    return skipEmpty - result;
}