Finding the longest common prefix.
Here’s an example Java program that finds the longest common prefix among an array of strings:
public class LongestCommonPrefix { public static String findLongestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } // Start with the first string as the initial common prefix String prefix = strs[0]; // Iterate through the remaining strings for (int i = 1; i < strs.length; i++) { // Update the common prefix by comparing characters while (strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length() - 1); } // If the prefix becomes empty, there is no common prefix if (prefix.isEmpty()) { return ""; } } return prefix; } public static void main(String[] args) { String[] strings = {"flower", "flow", "flight"}; String longestCommonPrefix = findLongestCommonPrefix(strings); System.out.println("Longest common prefix: " + longestCommonPrefix); } }
In this example, the `findLongestCommonPrefix` method takes an array of strings as input and returns the longest common prefix as a string. It starts by initializing the `prefix` variable with the first string in the array. Then, it iterates through the remaining strings, updating the `prefix` by comparing characters. If the prefix becomes empty at any point, it means there is no common prefix, and an empty string is returned. Finally, in the `main` method, we provide an example array of strings and print the longest common prefix. In this case, the output will be:
Longest common prefix: fl
This indicates that the longest common prefix among the strings “flower”, “flow”, and “flight” is “fl”.