2.11 题目详解:在有空字符串中的有序字符串数组中查找

Chapter2: 时间复杂度分析、递归、查找与排序

11. 题目详解:在有空字符串中的有序字符串数组中查找

题目

有个排序后的字符串数组,其中散布着一些空字符串,编写一个方法,找出给定字符串(肯定不是空字符串)的索引

算法

其实就是用二分查找,本身字符串数组就是有序的,与查找数字的不同之处就在于字符串的大小比较方式不一样罢了,还有就是这里还有空字符串,所以选取mid时,如果遇到空字符串,使其往下移动一位就好

代码(java版)
public class 在有空字符串的有序字符串数组中查找 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String [] arr = {"a","","ac","","ad","b","","ba"};
        int res = indexOf(arr,"abc");
        System.out.println(res);
    }

    private static int indexOf(String[] arr, String target) {
        int begin = 0;
        int end = arr.length - 1 ;
        while(begin<=end){
            int indexOfMid = begin + ((end-begin)>>1);
            while(arr[indexOfMid].equals("")){
                indexOfMid++;
                // 千万要注意
                if (indexOfMid>end) {
                    return -1;
                }
            }
            if (arr[indexOfMid].compareTo(target)>0) {
                end = indexOfMid - 1;
            }else if (arr[indexOfMid].compareTo(target)<0) {
                begin = indexOfMid +1;
            }else {
                return indexOfMid;
            }
        }
        return -1;
    }

}
代码(C++版本)
#include<iostream>
#include<cstdlib>
using namespace std;

int indexOf(string[],int arrLen,string target); 

int main(){
    string arr[8]={"a","","ac","","ad","b","","ba"};//有序递增的字符串数组 
    int arrLen=sizeof(arr)/sizeof(arr[0]);//同样适用于获取字符串数组的长度 
    string target="kk";
    printf("%d",indexOf(arr,arrLen,target)); 
    return 0;
} 

int indexOf(string* arr,int arrLen,string target){
    int begin=0;
    int end=arrLen-1;
    while(begin<=end){
        int midIndex=begin+((end-begin)>>1);
        while(arr[midIndex] == ""){//空字符串""的大小与字符串比较可能会有奇怪的结果吧
            midIndex++;
            //避免越界
            if(midIndex>end){
                return -1;
            } 
        } 
        if(target > arr[midIndex]){//target比arr[midIndex]大 
            begin=midIndex+1;
        }
        else if(target < arr[midIndex]){
            end=midIndex-1;
        }
        else {
            return midIndex;
        } 
    }
    return -1;//找不到时 
} 
扩展

C++比较字符串,可以直接用 > < == 符号,也可以用C语言的方法 strcmpstrcmp 能用于比较两个字符数组,不能用来比较两个string ,可以用 theString.c_str() 方式将字符串转为 const char * 再代入,如srcmp(str1.c_str(),"abc");并且需要引入 <cstring> 头文件

对于函数 strcmp(str1,str2)

  1. 如果str1=str2,函数值为0。
  2. 如果str1>str2,函数值为一正整数。
  3. 如果str1<str2,函数值为一负整数。

参考资料

[1] 在有空字符串的有序字符串数组中查找

[2] C++字符串数组

[3] C++用strcmp比较两个字符串

[4] C++直接用操作符比较字符串

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值