LeetCode – Length of Last Word (Java)

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.

Java Solution

We can scan the string from the end. When there is a letter, start counting the number of letters. This should handle cases like ” a “.

public int lengthOfLastWord(String s) { 
    if(s==null || s.length() == 0)
        return 0;
 
    int result = 0;
    int len = s.length();
 
    boolean flag = false;
    for(int i=len-1; i>=0; i--){
        char c = s.charAt(i);
        if((c>='a' && c<='z') || (c>='A' && c<='Z')){
            flag = true;
            result++;
        }else{
            if(flag)
                return result;
        }
    }
 
    return result;
}

12 thoughts on “LeetCode – Length of Last Word (Java)”

  1. Without the `flag` +
    some comments +
    compare to space instead of a-z chars.


    int lengthOfLastWord(String s)
    {
    if (s == null || s.length() == 0) return 0;

    int length = 0

    for (int i = s.length() - 1 ; i >= 0 ; i--)
    {
    char c = s.charAt(i);

    // continue counting
    if (c != ‘ ‘)
    {
    length++;
    continue;
    }

    assert c == ‘ ‘;

    // Encountered another space at the end, like “abcd “.
    if (length == 0) continue;

    // Encountered space and we already have a word
    break;
    }

    return length;
    }

  2. The lastIndexOf() method may not be allowed during the interview. It’s a good idea to ask the interviewer first.

    Your code does not handle the cases like ” a ” or “a “.


  3. public static int lengthOfLastWord(String s) {
    if (s == null)
    return 0;

    int i = s.lastIndexOf(' ') + 1;
    System.out.println(s.length() - i);
    return s.length() - i;
    }

    Isn’t this simpler? it also handles Alphanumerics, hyphens and other special characters if needed.

  4. public int lengthOfLastWord(String s) {
    int count = 0;
    boolean flag = false;
    for(int i=s.length()-1; i>=0;i–){
    if(s.charAt(i)== ‘ ‘ && !flag){
    continue;
    }
    if(s.charAt(i)==’ ‘ && flag) break;
    count++;
    flag=true;
    }
    return count;
    }

  5. The if statement in the for-loop needs to be updated to include a hyphenated last word.

    if((c>=’a’ && c=’A’ && c<='Z') || c == '-')


  6. public int solution(String s) {
    if (s == null) {
    return 0;
    }
    s = s.trim();
    if (s.length() == 0) {
    return 0;
    }
    String[] words = s.split("\s");
    return words[words.length-1].length();
    }

  7. public class Solution {

    public int lengthOfLastWord(String s) {

    if (s.length() == 0 || s == null)

    return 0;

    int total_len = s.length();

    int lastWordLen = 0;

    for (int i = total_len – 1; i >= 0; i–) {

    char c = s.charAt(i);

    if ((c >= ‘a’ && c = ‘A’ && c 0)

    return lastWordLen;

    }

    }

    return lastWordLen;

    }

    }


  8. void FunctionRunner::FindLastWordSize_Test() {
    string str = "My Last word is Harry";
    size_t pos = str.find_last_of(" ");
    if (pos == string::npos) {
    cout << "Last word size: " << 0 << "n";
    } else {
    cout << "Last word size: " << str.length() - pos - 1 << "n";
    }
    }

  9. public int lengthOfLastWord(String s) {
    int lastSpace = 0;
    s = s.trim();
    for (int i = 0; i < s.length() ; i++) {
    if (s.charAt(i) == ' ') lastSpace = i + 1;
    }
    return s.length() – lastSpace;
    }

  10. You just doubled the space used :), but honestly in real world we all would do it because it’s faster to type.

  11. public int lengthOfLastWord(String s) {
    s = s.trim();
    String[] arr = s.split(” “);

    if(s.length() == 0){
    return 0;
    }
    else{
    return arr[arr.length-1].length();
    }
    }

Leave a Comment