Longest Common Prefix Function in Java
Problem Description
The function finds the longest common prefix string amongst an array of strings.
Solution
public class Main {
/**
* Finds the longest common prefix string amongst an array of strings.
*
* @param strs An array of strings.
* @return The longest common prefix string. If there is no common prefix, returns an empty string.
*/
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
// Find the shortest string in the array
String shortestStr = strs[0];
for (String str : strs) {
if (str.length() < shortestStr.length()) {
shortestStr = str;
}
}
// Compare characters at the same position in all strings
for (int i = 0; i < shortestStr.length(); i++) {
char c = shortestStr.charAt(i);
for (String str : strs) {
if (str.charAt(i) != c) {
return shortestStr.substring(0, i);
}
}
}
// If all characters match, return the shortest string
return shortestStr;
}
public static void main(String[] args) {
// Example 1
String[] strs1 = {"flower", "flow", "flight"};
System.out.println("Example 1: " + longestCommonPrefix(strs1)); // Output: "fl"
// Example 2
String[] strs2 = {"dog", "racecar", "car"};
System.out.println("Example 2: " + longestCommonPrefix(strs2)); // Output: ""
}
}
Explanation
- Check if the input array is null or empty. If so, return an empty string.
- Find the shortest string in the array, as the common prefix cannot be longer than this string.
- Iterate through each character in the shortest string and compare it with the corresponding character in all other strings.
- If a mismatch is found, return the substring of the shortest string up to the mismatched character.
- If all characters match, return the shortest string as the common prefix.
Time Complexity
The time complexity of this solution is O(n * m), where n is the length of the input array and m is the length of the shortest string.
Space Complexity
The space complexity is O(1), excluding the space required for the input and output strings.