Cracking the coding interview--Q9.5

原文:

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);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值