Longest Common Prefix
Problem
The line has several words separated by spaces. Print the longest prefix that all words share. Print none if there is no common prefix.
Constraints
- 1 <= words <= 1000
Examples
Input
flower flow flight
Output
fl
Solutions
The prefix can only get shorter. An empty string always matches startsWith, so the while loop always stops.
/*
* Problem : Process text.
* Input : One line of text.
* Output : The common prefix.
* Approach: Shorten the first word.
* Time : O(total characters)
* Space : O(1)
* 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 line into words. The first word is our first guess for the prefix.
String[] words = s.trim().split("\\s+");
String prefix = words[0];
// Step 2: For each next word, shorten the prefix until the word starts with it.
for (int i = 1; i < words.length; i++) {
while (!words[i].startsWith(prefix)) {
prefix = prefix.substring(0, prefix.length() - 1);
}
}
// Step 3: An empty prefix means there is no common prefix.
return prefix.isEmpty() ? "none" : prefix;
}
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)
- Why does the while loop always end?