原文:
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.
字符串数组已经是有序的了,所以,还是可以利用二分查找来找到指定的字符串。 当然了,由于数组中有空字符串,因此还要加些额外的处理,否则无法对比大小。 我们可以这样来处理,如果要对比的那个元素为空字符串,就一直向右移动, 直到字符串不为空或是位置已经超出了high下标。如果位置已经超出high下标, 就在[low, mid-1]这一段查找;如果没有超出high下标,那就和要查找的x进行对比。 相等时返回下标,不等时再根据比较出的大小决定到哪一半去查找。
package chapter_9_SortingandSearching;
/**
*
* 给你一个排好序的并且穿插有空字符串的字符串数组,写一个函数找到给定字符串的位置。
*
*/
public class Question_9_4 {
/**
* @param str
* @param find
* @return
*
* 如果要对比的那个元素为空字符串,就一直向右移动, 直到字符串不为空或是位置已经超出了high下标。
* 如果位置已经超出high下标, 就在[low, mid-1]这一段查找;如果没有超出high下标,那就和要查找的x进行对比。
* 相等时返回下标,不等时再根据比较出的大小决定到哪一半去查找。
*
*/
public static int findIndex(String str[], String find) {
if(find.equals("")) {
return -1;
}
int start = 0;
int end = str.length - 1;
while(start <= end) {
int mid = (start + end) / 2;
int shift = mid;
while(str[mid].equals("") && mid <= end) {
mid ++;
}
if(mid > end || (str[mid].compareTo(find) > 0)) {
end = shift - 1;
} else if(str[mid].compareTo(find) < 0) {
start = mid + 1;
} else {
return mid;
}
}
return -1;
}
public static void main(String args[]) {
String[] strs = new String[]{"abc", "", "", "", "bcd", "bdd", "cdd", "","", "", "ddd"};
String find = "ddd";
int index = findIndex(strs, find);
System.out.println("index:" + index);
}
}