Java -- 字符串匹配算法

字符串匹配算法:就是给定两个串,查找另一个串是否在主串里面,在这里,我们讨论的时候主要用字符串来实现。

  • 什么是串?
    由零个或多个字符组成的有序序列:‘abcdef’

  • 串的长度:串中字符的数目成为串的长度

  • 空串:什么都没有;“ ”有空格的叫做空格串

  • 子串:子串包含空串和串本身

  • 子串在主串中的位置:
    在这里插入图片描述
    一、BF算法
    https://blog.csdn.net/deepseazbw/article/details/75896335

package com.impl;

/**
 * @program: sadd
 * @description:
 * @author: 
 * @create: 2019-01-09 09:58
 **/
public class TestBFDemo {
    public static int bf(String str,String sub){
        int i = 0;
        int j = 0;
        while(i < str.length()){
            while(j < sub.length()){
                if(str.charAt(i) == sub.charAt(j)){
                    i++;
                    j++;
                }else{
                    i = i-j+1;
                    j =0;
                }
            }
            break;
        }
        return i-j;
    }

    public static void main(String[] args) {
        String str = "ababcabcdabcde";
        String sub = "abcd";
        int n = TestBFDemo.bf(str,sub);
        System.out.println(n);
    }
}

二、KMP算法
https://blog.csdn.net/liu940204/article/details/51318281

猜你喜欢

转载自blog.csdn.net/xyxy66/article/details/86135025
今日推荐