暴力匹配算法

暴力匹配的方式很简单,就是一个个的对比,当有一个不对的时候则将要找的数据从头计算,被找的数据继续往下寻找,直到被找数据对比完成,找到返回下标,没有返回 -1 

public class ViolenceMatch {

    public static void main(String[] args) {
        String str1 = "223 123412 123412341245";
        String str2 = "1234124";
        int index = violenceMatch(str1, str2);
        System.out.println(index);//15

    }

    public static int violenceMatch(String str1, String str2) {
        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int s1Len = s1.length;
        int s2Len = s2.length;

        int i = 0;
        int j = 0;
        while (i < s1Len && j < s2Len) {
            if (s1[i] == s2[j]) {
                i++;
                j++;
            } else {
                i = i - (j - 1);
                j = 0;
            }
        }
        if (j == s2Len) {
            return i - j;
        } else {
            return -1;
        }
    }
}
posted @ 2020-02-25 10:27  Axs  阅读(703)  评论(0)    收藏  举报