使用Sunday算法实现字符串查找

//实现 strStr() 函数。
//
// 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如
//果不存在,则返回 -1。
//
// 示例 1:
//
// 输入: haystack = "hello", needle = "ll"
//输出: 2
这是leetcode上的题,网上有很多使用kmp算法解决的,但是kmp的next数组求解实在太复杂了,我就使用了一个更简单的算法。

public int strStr(String haystack, String needle) {
            int x = 0;
            int y = 0;
            int len1 = haystack.length();
            int len2 = needle.length();
            while (x < haystack.length() && y < needle.length()) {
                if (haystack.charAt(x) == needle.charAt(y)) {
                    x++;
                    y++;
                    System.out.print(x);
                    System.out.println(":"+y);
                } else if (haystack.charAt(x) != needle.charAt(y) &&(x - y + len2)

你可能感兴趣的:(使用Sunday算法实现字符串查找)