diff --git a/string.java b/string.java new file mode 100644 index 0000000..b6adec0 --- /dev/null +++ b/string.java @@ -0,0 +1,22 @@ +class Solution { + public String longestCommonPrefix(String[] strs) { + if (strs == null || strs.length == 0) + return ""; + + // Take the first string as the reference + String prefix = strs[0]; + + // Compare the prefix with each string in the array + for (int i = 1; i < strs.length; i++) { + // While the current string doesn't start with the prefix + while (strs[i].indexOf(prefix) != 0) { + // Shorten the prefix by one character + prefix = prefix.substring(0, prefix.length() - 1); + + // If prefix becomes empty, no common prefix exists + if (prefix.isEmpty()) return ""; + } + } + return prefix; + } +}