Longest Word in a Sentence

easy Strings

Problem

Read a sentence of words separated by spaces. Print the longest word. If two words have the same length, print the one that comes first.

Constraints

  • 1 <= length <= 10^5

Examples

Input

I love programming in Java

Output

programming

Solutions

Best approachTime O(n)Space O(n)

Using > (not >=) keeps the first word when two words have the same length. A max with a key function does the same in Python.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process text.
 * Input   : One line of text.
 * Output  : The longest word.
 * Approach: Compare lengths.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(String s) {
        // Step 1: Split the sentence into words at one or more spaces.
        String[] words = s.trim().split("\\s+");
        String best = "";

        // Step 2: Replace the best word only when a word is strictly longer. So the first of equal words stays.
        for (String word : words) {
            if (word.length() > best.length()) {
                best = word;
            }
        }
        return best;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.hasNextLine() ? scanner.nextLine() : "";
        System.out.println(solve(s));
    }
}
Hints (1)
  1. What changes if you use >= ?