2
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;
}
mkrieger1
  • 10,793
  • 4
  • 39
  • 47
Kamal Kumar
  • 194
  • 11

2 Answers2

0

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.

Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
0

Or using stream:

String[] num = { "1201", "12018", "1201800","12018000" };
String prefix = "120180000175135";
    
Optional<String> match = Arrays.asList(num).stream()
    .sorted(Comparator.comparingInt(String::length).reversed())
    .filter(prefix::startsWith)
    .findFirst();
System.out.println("Longest match is: " + match.orElse("no match found"));
Tyler2P
  • 1,391
  • 1
  • 9
  • 18