使用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)<len1&&
                        needle.contains(String.valueOf(haystack.charAt(x - y + len2)))
                ) {
                    int x2 = needle.lastIndexOf(haystack.charAt(x - y + len2));
                    System.out.println(x2);
                    x = x - y + len2 - x2;
                    y = 0;
                } else if (haystack.charAt(x) != needle.charAt(y) &&(x - y + len2)<len1&&
                        !needle.contains(String.valueOf(haystack.charAt(x - y + len2)))
                ){
                    x = x - y + len2 + 1;
                    System.out.println("three:"+x);
                    y = 0;
                }else {
                    return -1;
                }
            }
            if (y ==len2){
                return x-y;
            }else {
                return -1;
            }
        }
//解答成功: 执行耗时:153 ms,击败了5.03% 的Java用户 
//内存消耗:40.2 MB,击败了5.43% 的Java用户
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。