Interview 150

Length of Last Word

Problem
LC 58
File
interview150_LC58LengthOfLastWord.java
Path
pkg5leetcode/interview150/interview150_LC58LengthOfLastWord.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC58LengthOfLastWord.java
Approach
Scan from end skipping trailing spaces; count last word.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/interview150/interview150_LC58LengthOfLastWord.java
1package pkg5leetcode.interview150;2 3/*4 * Length of Last Word | LC 585 * APPROACH: Scan from end skipping trailing spaces; count last word.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC58LengthOfLastWord {9    static int lengthOfLastWord(String s) {10        int i = s.length() - 1;11        while (i >= 0 && s.charAt(i) == ' ') i--;12        int len = 0;13        while (i >= 0 && s.charAt(i) != ' ') { len++; i--; }14        return len;15    }16 17    public static void main(String[] args) {18        check(lengthOfLastWord("Hello World") == 5, "case1");19        check(lengthOfLastWord("   fly me   to   the moon  ") == 4, "case2");20        System.out.println("all tests passed");21    }22 23    static void check(boolean cond, String name) {24        if (!cond) throw new AssertionError("FAILED: " + name);25        System.out.println("  PASS " + name);26    }27}