BF算法

BF算法,即Brute Force 算法的简称。用于检测某个字符串是否是另一个字符串的子串。

子串的概念

假设字符串 X = 'girlfriend' , Y = 'friend' ,那么Y 就是 X的子串。同样的,endfriend的子串。

BF算法的思路

BF算法的思路非常简单粗暴,就是从前到后一点点的匹配。例如: 子串 x= abcd | 主串为 y = abdabceabcde
如果 x[0] = y[0] 继续比较 x[1] y[1] 继续下去,如果一直到 x[3]= y[3]时 则 x 整个串都匹配上了。
如果 x[0] = y[0] 继续比较 x[1] y[i] 发现不等,那么就开始用 x[0] 比较 y[1] 然后继续 x[1] y[2]。

第一步

abdabceabcde
abcd

匹配到第三个位置的时候,上面是d,下面是c,于是开始第二部。

第二步

abdabceabcde
-abcd

第三步

abdabceabcde
--abcd

第四步

abdabceabcde
---abcd

……
直到 主串的 第7个位置(从0开始计数)开始终于匹配上了。

Java 代码实现

public class BruteForce {

    public static void main(String[] args) {
        System.out.println(isSubstring("abdabceabcde","abcd")); // true
        System.out.println(isSubstring("abdabceabcde","ff"));   // false
    }

    private static boolean isSubstring(String main,String sub){
        if(main == null || sub == null) {
            return false;
        }
        if(main.length() < sub.length()) { // 主串要长于子串
            return false;
        }
        if(main.equals(sub)) { // 主串,子串 相等的情况
            return true;
        }
        int len = main.length() - sub.length();
        for (int i = 0; i < len; i++) {
            boolean match = true;
            for (int j = 0; j < sub.length(); j++) {
                if(main.charAt(i+j) != sub.charAt(j)) {
                    match = false;
                    break;
                }
            }
            if(match) {
                return true;
            }
        }
        return false;
    }

}
原文地址:https://www.cnblogs.com/demingblog/p/9711464.html