zoukankan      html  css  js  c++  java
  • 字符串匹配暴力匹配优化

    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、尽量远地向后移动目标串,而不是一位一位的移动。

  • 相关阅读:
    implementaion bottle session with beaker
    [梦]20050802
    网站更新部署20100912
    Cherokee不值得推荐,你还是可以看一看
    最简单方法远程调试Python多进程子程序
    nginx相关的问题
    本地配置host解析的问题
    base target问题,
    在asp.net中自动合并小图片并使用css sprite显示出来
    html编辑器
  • 原文地址:https://www.cnblogs.com/cherish010/p/10489552.html
Copyright © 2011-2022 走看看