要点是找到最近的不是空字符串的位置,然后作为mid,再继续二分
package Sorting_Searching;
/**
* Given a sorted array of strings which is interspersed with empty strings,
* write a method to find the location of a given string.
*
* Example: find “ball” in [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”,“”,
* “dad”, “”, “”] will return 4
*
* Example: find “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”,
* “dad”, “”, “”] will return -1
*
* 译文:
*
* 给你一个排好序的并且穿插有空字符串的字符串数组,写一个函数找到给定字符串的位置。
*
* 例子:在字符串数组 [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”,“”, “dad”, “”, “”]
* 中找到"ball",返回下标4.
*
* 例子:在字符串数组 [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”, “”]
* 中找到"ballcar",查找失败,返回-1.
*
*/
public class S11_5 {
public static void main(String[] args) {
String[] stringList = { "apple", "", "", "banana", "", "", "",
"carrot", "duck", "", "", "eel", "", "flower" };
System.out.println(search(stringList, "apple"));
}
public static int search(String[] strings, String str) {
if (strings == null || str == null || str.isEmpty()) {
return -1;
}
return searchR(strings, str, 0, strings.length - 1);
}
public static int searchR(String[] strings, String str, int first, int last) {
if(first > last){
return -1;
}
int mid = (first+last)/2;
// 找到离中心最近的不是空字符串的位置
if(strings[mid].length() == 0 && mid<=last){
int left = mid-1;
int right = mid+1;
while(true){
if(left<first && right>last){
return -1;
}else if(right<=last && strings[right].length()!=0){
mid = right;
break;
}else if(left>=first && strings[left].length()!=0){
mid = left;
break;
}
right++;
left--;
}
}
if(str.equals(strings[mid])){
return mid;
}else if(strings[mid].compareTo(str) > 0){
return searchR(strings, str, first, mid-1);
}else {
return searchR(strings, str, mid+1, last);
}
}
}