你作为一个Java领域的专家,请完成以下任务:最左前缀索引
时间: 2023-12-03 09:43:18 浏览: 34
最左前缀索引(Leftmost Prefix Index)是指在一个字符串数组中,对于某个查询串,找到第一个以该查询串为前缀的字符串的索引位置。如果不存在这样的字符串,则返回-1。
以下是一个Java实现示例:
```java
public class LeftmostPrefixIndex {
public static int findLeftmostPrefixIndex(String[] arr, String query) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].startsWith(query)) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
String[] arr = {"apple", "banana", "orange", "pear"};
String query1 = "app";
String query2 = "pea";
System.out.println(findLeftmostPrefixIndex(arr, query1)); // Output: 0
System.out.println(findLeftmostPrefixIndex(arr, query2)); // Output: 3
}
}
```
在这个示例中,我们定义了一个静态方法`findLeftmostPrefixIndex`,它接受一个字符串数组和一个查询串作为参数,返回最左前缀索引。在方法内部,我们使用一个for循环遍历字符串数组,对于每个字符串,使用`startsWith`方法判断是否以查询串为前缀,如果是,则返回当前索引位置。如果没有找到满足条件的字符串,则返回-1。
在main方法中,我们定义了一个字符串数组和两个查询串,分别调用`findLeftmostPrefixIndex`方法,并输出结果。