Learn-dsa..in 30 days!



























CC-15 : Find longest common prefix.

Description:

Given input array of Strings strArr, find the common sequence of characters that is present at start (prefix) of each of the Strings in the array and return the prefix.

Test cases and expected outputs:

Input Parameters Expected outputs
The input string array is: autopilot, automatic, autofocus, autobiography Longest common prefix: auto
The input string array is: copilot, coworker, cooperate Longest common prefix: co
The input string array is: house, plane, pledge No common prefix exists

Pseudocode:

The java method should accept following input parameters: strArr (String[]).
Set String variable pre=strArr[0], this sets pre to first String of the array.
Using a for loop, search whether each of the other words in strArr begins with pre. If yes, pre is the longest common prefix.
Else we will remove one last character from pre and set the remaining string without last character to pre again.
Now repeat above step till either pre is present at start of all Strings in strArr or until pre become blank.
If pre becomes blank, it means no common prefix exists.
Return pre.

Code:

public String stringLongestCommonPrefix(String[] strArr) {
	String pre=strArr[0];
	for (int idx=1; idx < strArr.length; idx++) {
		while ((!pre.equals("") && (strArr[idx].startsWith(pre)==false))) {
			pre=pre.substring(0, pre.length()-1);			
		}
	}
	return pre;
}

Click here to download and run code and test cases !