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

原文地址:https://www.cnblogs.com/a1439775520/p/13078021.html