Sort array of strings

本文探讨了在包含空字符串的已排序字符串数组中寻找特定字符串位置的算法,详细介绍了边界用例和优化策略,包括特殊用例处理、函数实现与代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 首先我要在纸上,非常非常聪明且迅速且机灵,
  2. 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
  3. 向面试官提问:问题规模,特殊用例
  4. 给出函数头
  5. 暴力解,简述,优化。
  6. 给出能够想到的最优价
  7. 伪代码,同时结合用例
  8. 真实代码




Given a sorted array of strings which is interspersed with empty strings, write a meth-

od to ind the location of a given string.   

Example:  ind  “ball”  in  [“at”,  “”,  “”,  “”,  “ball”,  “”,  “”,  “car”,  “”,  “”,  “dad”,  “”,  “”]  will  return  4 
Example: ind “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”, “”] will return -1


/*
"at", "az", "", "", "ba", "", "bbb"
ba
"at", "az", "", "", "ba", "", "bbb"

a a a a a a a a b;     find a
        |
a a b b b b b b b;     find a
        |
[] [] [] [] ; find []    
        
mid =

1. find the mid string
2. compare mid string with target
3. two cases:  target < arr[mid] -> set l=mid 
            or target >= arr[mid] -> set u=mid
            
*/

bool compare(string &m, string &target)
{
    return target < m;
}

int find(const vector<string> &arr, string &target)
{
    
    int u=arr.size();
    int l=0;
    
    if(target=="")
    {
        for(int i=0; i<arr.size(); i++)
        {
            if(arr[i]=="") return i;
        }
        return -1; // can not find the target   
    }
    
    while(l<u-1)
    {
        int mid = l + (u-l)/2;
        
        // step forward to find the first non-empty
        while(arr[mid].empty())
        {
            if(mid==u) break;
            mid++;                
        }
        
        // If there is no non-empty string forward
        if(mid==u)
        {
            mid = l + (u-l)/2;
            while(arr[mid].empty())
            {
                if(mid==-1) return -1; // can not find target.
                mid--;
            }
        }       
        
        bool rst = compare(arr[mid], target);
        if(rst) // target < arr[mid]
        {
            l = mid-1;
        }
        else
        {
            u = mid;
        }        
    }    
    
    if(arr[l] == target)
    {
        return l;
    }
    else
        return -1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值