22. Finding the longest common prefix

Let's consider the following array of strings:

String[] texts = {"abc", "abcd", "abcde", "ab", "abcd", "abcdef"};

Now, let's put these strings one below the other, as follows:

abc
abcd
abcde
ab
abcd
abcdef

A simple comparison of these strings reveals that ab is the longest common prefix. Now, let's dive into a solution for solving this problem. The solution that we've presented here relies on a straightforward comparison. This solution takes the first string from the array and compares each of its characters in the rest of the strings. The algorithm stops if either of the following happens:

  • The length of the first string is greater than the length of any of the other strings
  • The current character of the first string is not the same as the current character of any of the other strings

If the algorithm forcibly stops because of one of the preceding scenarios, then the longest common prefix is the substring from 0 to the index of the current character from the first string. Otherwise, the longest common prefix is the first string from the array. The code for this solution is as follows:

public static String longestCommonPrefix(String[] strs) {

if (strs.length == 1) {
return strs[0];
}

int firstLen = strs[0].length();

for (int prefixLen = 0; prefixLen < firstLen; prefixLen++) {
char ch = strs[0].charAt(prefixLen);
for (int i = 1; i < strs.length; i++) {
if (prefixLen >= strs[i].length()
|| strs[i].charAt(prefixLen) != ch) {
return strs[i].substring(0, prefixLen);
}
}
}

return strs[0];
}

Other solutions to this problem use well-known algorithms such as Binary Search or Trie. In the source code that accompanies this book, there is a solution based on Binary Search as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.33.235