字符串匹配暴力匹配优化

1、字符串匹配问题:给定一个字符串,求子串在该字符串中的位置索引

暴力求解:穷举所有位置s=0,s=1....s=n-m,判断长度m的串是否每一位与目标串相同,时间复杂度:O((n-m=1)*m).

优化思路:

  1. 从右向左匹配,如果遇到了不匹配的a-b,则寻找下一个目标串的最右字符,对齐匹配
  2. 下一字符位移i,则整个串位移i
  3. 没有下一个字符,结束匹配
public static List<Integer> matches(String text, String target) {
        char[] total = text.toCharArray();
        char[] str = target.toCharArray();
        int textSize = total.length;
        int targetSize = str.length;
        List<Integer> count = new ArrayList<Integer>();
        if (targetSize > textSize) {
            count.add(0);
            return count;
        }
        for (int i = 0; i <= (textSize - targetSize);){
            boolean ok = true;
            for (int j = 0; j < targetSize; j++) {
                if(total[(i + (targetSize - 1)) -j]!= str[(targetSize - 1) -j]) {
                    ok = false;
                }
            }
            if (ok) {//匹配成功
                count.add(i);
                i++;
            }else{//匹配失败
                int move = 1;
                boolean find = false;
                for(;i+targetSize -1 + move < textSize;move++){
                    if(total[i + targetSize -1 + move] == str[targetSize -1]) {
                        find = true;
                        break;
                    }
                }
                if(!find) {
                    break;
                }else {
                    i +=move;
                    System.out.println("比较优化的位移:" +move);
                }
            }
        }
        for (Integer index : count){
            System.out.println("查找到的子串:"+index);
        }
        return count;
    }

    public static void main(String[] args) {
        String text = "abchjabciwahcashhcashaj";
        String str = "abc";
        matches(text, str);
    }

打印结果:

比较优化的位移:4
比较优化的位移:4
比较优化的位移:5
查找到的子串:0
查找到的子串:5

总结:1、充分利用不匹配时,两个字符串的内容信息。

         2、尽量远地向后移动目标串,而不是一位一位的移动。

 

转载于:https://www.cnblogs.com/cherish010/p/10489552.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值