leetcode1055

在这里插入图片描述
在这里插入图片描述
暴力查询即可,外面一层遍历target字符串,内层对source进行遍历,直到当前的内层遍历source中已无可匹配字符,在进行下一次source遍历,直到外层遍历结束。最终统计进行了几次内层遍历。
优化的方法:将内层遍历改为二分查找,进而衍生的需要用map存储source的每个字符对应的下标的列表。

public class test {
    public int shortestWay(String source, String target){
        Map<Character, List<Integer>> map = getCharIndexs(source);
        int res = 1;
        int index = -1;
        for(int i=0; i<target.length(); i++){
            char ch = target.charAt(i);
            int nextIndex = bsearch(map, ch, index);
            if(nextIndex == -1 && index == -1){
                return -1;
            }else if(nextIndex == -1){
                res++;
                index = -1;
                i--;
            }else{
                index = nextIndex;
            }
        }
        return res;
    }

    private Map<Character, List<Integer>> getCharIndexs(String src){
        Map<Character, List<Integer>> map = new HashMap<>();
        for(int i=0; i<src.length(); i++){
            char ch = src.charAt(i);
            map.computeIfAbsent(ch, k -> new ArrayList<>()).add(i);
        }
        return map;
    }

    private int bsearch(Map<Character, List<Integer>> map, char ch, int index){
        if(!map.containsKey(ch)){
            return -1;
        }
        List<Integer> array = map.get(ch);
        int l=0;
        int r=array.size()-1;
        while(l<r){
            int mid = l + (r-l)/2;
            if(array.get(mid) <= index){
                l = mid + 1;
            }else{
                r = mid;
            }
        }
        return array.get(l) > index ? array.get(l) : -1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值