javaarraysstringprefixlongest-substring

How to find longest prefix from array list using given string value in Java?


String[] num = { "1201", "12018", "1201800","12018000" };

String prefix="120180000175135";

I have two variables one is String array and other one is String. Now I want to get longest value from String array using prefix. Please suggest me how can I do it in Java.

Please review also my solution but it does not work in above condition.

private static Item binarySearch(Item[] a, String key) {
    int low = 0;
    System.out.println("a.length" + a.length);
    int high = a.length - 1;

    while (low <= high) {
        int mid = (low + high) >>> 1;
        int len = Math.min(key.length(), a[mid].key.length());
        String midVal = a[mid].key.substring(0, len);
        String cmpKey = key.substring(0, len);
        if (midVal.compareTo(cmpKey) > 0)
            low = mid + 1;
        else if (midVal.compareTo(cmpKey) < 0)
            high = mid - 1;
        else
            return a[mid];
    }
    return null;
}

Solution

  • Assuming your array of numbers be sorted ascending by length, you could iterate backwards and use String#startsWith, printing the first match:

    String[] num = { "1201", "12018", "1201800","12018000" };
    String prefix = "120180000175135";
    
    for (int i=num.length-1; i >= 0; i--) {
        if (prefix.startsWith(num[i])) {
            System.out.println("Longest match is: " + num[i]);
            break;
        }
    }
    

    If the array of numbers is not already sorted, then you could either do a sort, or instead you would have to iterate the entire unsorted array and keep track of the length of each match.