BruteSubstringSearch2

賈小強
转载请注明原创出处,谢谢!

package com.lab1.test5;

public class BruteSubstringSearch2 {
    public static void main(String[] args) {
        String txt = "aaabbcc";
        String pat = "bb";
        System.out.println(txt);
        for (int i = 0; i < search(pat, txt); i++) {
            System.out.print(" ");
        }
        System.out.print(pat);
    }

    private static int search(String pat, String txt) {
        int m = pat.length();
        int n = txt.length();
        int i, j;
        for (i = 0, j = 0; i < n && j < m; i++) {
            if (txt.charAt(i) == pat.charAt(j)) {
                j++;
            } else {
                i -= j;
                j = 0;
            }
        }
        if (j == m) {
            return i - m;
        } else {
            return n;
        }
    }
}

输出

aaabbcc
   bb

Happy learning !!

你可能感兴趣的:(BruteSubstringSearch2)