zoukankan      html  css  js  c++  java
  • Java实现字符串匹配

    1 问题描述
    给定一个n个字符组成的串(称为文本),一个m(m <= n)的串(称为模式),从文本中寻找匹配模式的子串。

    2 解决方案
    2.1 蛮力法

    package com.liuzhen.chapterThree;
    
    public class BruteForceStringMatch {
        //根据文本串N,和模式串M,返回第一个匹配模式串的子串在N中的位置
        public static int getStringMatch(int[] N , int[] M){
            int n = N.length;          //文本串的长度
            int m = M.length;          //模式串的长度
            for(int i = 0;i < n-m;i++){       //最后一轮子串匹配的起始位置是n-m,如果大于n-m一定不会出现匹配子串
                int j = 0;
                while(j < m && M[j] == N[i+j])
                    j = j +1;
                if(j == m)
                    return i;
            }
            return -1;
        }
        
        public static void main(String args[]){
            int[] N  = {1,2,3,2,4,5,6,7,8,9};
            int[] M = {6,7,8};
            int position = getStringMatch(N,M);
            System.out.println("文本串N中第"+position+"位开始,可以寻找一个匹配模式M的子串,该位置字符值为:"+N[position]);
        }
    }
    

    运行结果:
    文本串N中第6位开始,可以寻找一个匹配模式M的子串,该位置字符值为:6

    2.2 KMP模式匹配法

    package com.liuzhen.practice;
    
    public class Main {
        //获取匹配字符串B的next函数值
        public int[] getNext(String B) {
            char[] arrayB = B.toCharArray();
            int[] next = new int[arrayB.length + 1];
            int j = 0;
            for(int i = 1;i < arrayB.length;i++) {
                while(j > 0 && arrayB[i] != arrayB[j])
                    j = next[j];
                if(arrayB[i] == arrayB[j])
                    j++;
                next[i + 1] = j;
            }
            return next;
        }
        //输出B在A中出现匹配子串所有情况的第一个位置
        public void getKMP(String A, String B) {
            int[] next = getNext(B);
            char[] arrayA = A.toCharArray();
            char[] arrayB = B.toCharArray();
            int j = 0;
            for(int i = 0;i < arrayA.length;i++) {
                while(j > 0 && arrayA[i] != arrayB[j])
                    j = next[j];
                if(arrayA[i] == arrayB[j])
                    j++;
                if(j == arrayB.length) {
                    System.out.println("开始匹配位置:"+(i - j + 1));
                    j = 0;       //重新开始新的匹配检查
                }
            }
            return;
        }
        
        public static void main(String[] args) {
            Main test = new Main();
            String A = "bbaabbbbbaabbbbaabb";
            String B = "bbbaa";
            test.getKMP(A, B);
        }
    }
    

    运行结果:

    开始匹配位置:6
    开始匹配位置:12

  • 相关阅读:
    li中下的a元素的字超出了li的宽度
    0 ‘+new Array(017)’ 输出? js+相当于Number()类型转换
    通过字体代替图片优化,如何使用Font Awesome字体图标?
    Array.prototype.slice.call()等几种将arguments对象转换成数组对象的方法
    js关于if()else{}中的判定条件的认识,各种数据类型转换为Boolean类型的转换规则
    js基本包装类型
    WordPress启用memcached动态缓存,弄了好久终于弄好了
    VsCode最实用插件集合
    Cordova--IOS打包问题汇总
    cordova--安卓打包
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12948098.html
Copyright © 2011-2022 走看看