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.

Solution

My original Solution using split() and trim(): O(1) time, O(1) space

public class Solution {
    public int lengthOfLastWord(String s) {
        if (s == null || s.length() == 0) return 0;
        String[] words = s.split("\\s");
        if (words.length == 0) return 0;
        return words[words.length - 1].length();
    }
}

Backwards Iteration with no String Library used

public class Solution {
    public int lengthOfLastWord(String s) {
        if (s == null || s.length() == 0) return 0;
        int res = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == ' ' && res == 0) continue;
            if (s.charAt(i) == ' ') return res;
            res++;
        }
        return res;
    }
}

Another Backwards Iteration

public class Solution {
    public int lengthOfLastWord(String s) {
        if (s == null || s.length() == 0) return 0;
        int index = s.length() - 1, res = 0;
        while (index >= 0 && s.charAt(index) == ' ') index--;
        while (index >= 0 && s.charAt(index--) != ' ') res++;
        return res;
    }
}

Analysis

Although the first solution is O(1) time, it might be not welcomed in a real interview
The interviewer might ask you to implement and split()

The iterative solutions are pretty straightforward
Notice that we need to consider case like "a ", hence we need two if statements in the second solution

results matching ""

    No results matching ""