Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
The intention of the topic
It seems that it was not a check between pair of strings but on all the strings in the array.
For example:
{"A", "a", "B"} should give "" as there are nothing common the 3 strings.
{"A", "a"} should give "a" as a are longest common prefix in all the strings.
{"ABCA", "ABC"} AS ABC
{"AC", "AC", "a", "a"} as a.
Logic goes something like this:
Pick a character at i=0th location and compare it with the character on that location in every string.
If anyone doesn ' t has that just return ""
Else append that character on to the result.
Increment I and do steps 1-3 till the length of this string.
return result.
Make sure proper checks is maintained to avoid index out of bounds error.
Code
Public class Solution { Public Static String Longestcommonprefix (string[] STRs) {if (STRs == NULL || Strs.length == 0)return "";String Pre = strs[0];int I = 1; while (i < strs.length) {System.out.println (Strs[i].indexof (PRE) ); while (Strs[i].indexof (PRE) != 0)Pre = pre.substring (0, pre.length () - 1);I++;}return Pre;}}
"Leetcode" Longest Common Prefix