Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find longest common prefix?

Tags:

java

In two strings:

"Mary Had a Little Lamb"
"Mary Had a Big Lamb"

should return

"Mary Had a "

like image 238
KJW Avatar asked Nov 07 '11 07:11

KJW


People also ask

How do you find the longest prefix match?

The Longest Match Routing Rule is an algorithm used by IP routers to select an entry from a routing table. The router uses the longest (prefix) match to determine the egress (outbound) interface and the address of the next device to which to send a packet.

How do you find the longest common prefix in Javascript?

So the first step, after checking for valid input, would be to sort the given array in order of shortest string to longest string. The next step would be to take the shortest string, and check each string to see if it begins with that string.

How do you find the longest common prefix between two strings?

Longest common prefix (LCP) for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1 and S2. For Example: longest common prefix of “abcdefgh” and “abcefgh” is “ABC”.


1 Answers

You don't need to use a StringBuilder - just return the substring:

public String greatestCommonPrefix(String a, String b) {
    int minLength = Math.min(a.length(), b.length());
    for (int i = 0; i < minLength; i++) {
        if (a.charAt(i) != b.charAt(i)) {
            return a.substring(0, i);
        }
    }
    return a.substring(0, minLength);
}
like image 177
3 revs Avatar answered Sep 17 '22 15:09

3 revs