实现 strStr() 函数-算法刷题

算法题目

实现 strStr() 函数:

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的
第一个位置 (从0开始)。如果不存在,则返回 -1。

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2

示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1

说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的
indexOf() 定义相符

/**

@author cosefy

@date 2020/7/2
*/
public class StrStr {
public static void main(String[] args) {
    String haystack = "aaaba";
    String needle = "sssssss";
    int res1 = test1(haystack, needle);
    System.out.println(res1);
}

//解法一
/*
思路:1,判断模式串是否为空,空则返回0,判断模式串的长度是否大于主串,大于则返回-1.
     2,如果子串和主串第一个字符不相同则直接向后移动主串
     3,如果部分匹配,则需要主串回退,此处可以利用一个辅助变量代替主串前进,可以省略回退。
 */
private static int test1(String haystack, String needle) {
    int n = needle.length();
    if (n == 0)
        return 0;
    int h = haystack.length();
    if (n > h)
        return -1;
    for (int i = 0; i < h - n + 1; i++) {
        int temp = i, j = 0;   //利用temp变量来代替主串元素往后比较,可以省略匹配失败后主串的回退
        for (; j < n; j++) {
            if (haystack.charAt(temp++) != needle.charAt(j))
                break;
        }
        if (j == n) //第二个for循环完全执行完之后j=n,说明完全匹配。
            return i;
    }
    return -1;


​    }

​    //解法二:KMP算法
}
posted @ 2020-07-02 19:42  cosefy  阅读(172)  评论(0编辑  收藏  举报