字符串匹配算法--BF算法

BF( Brute force)算法,又称暴力搜索。
思想:首先将原字符串和要匹配的字符串(以下简称子串)左端对齐,之后比较第一个字符相同则继续比较第二个字符,直至全部匹配;如果不同将子串向后移动一位再继续比较。如图所示:
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
JAVA实现demo:

class BF
{
    String total_string;
    String sub_string;
    public BF(String a,String b)
    {
       total_string=a;
       sub_string=b;

    }
    public int find()
    {
        int i;      
        for(i=0;i<=total_string.length()-sub_string.length();i++)
        {
            int j=0;
            int q=i;
            while(total_string.substring(q,q+1).equals(sub_string.substring(j,j+1)))
            {
                j++;
                q++;
                if(j==sub_string.length()-1)
                    return i;
            } 
        }
        return -1;
    }
    public static void main(String[] args)
    {
       BF b=new BF("ABCDEF","DEF");
       System.out.println(b.find());
    }
}

时间复杂度为O(MN),M代表长串的长度,N代表子串的长度。

猜你喜欢

转载自blog.csdn.net/osa1993/article/details/51924766