实现 strStr() 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 。如果不存在,则返回 -1 面试算法

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

 public static  int strStr1(String haystack, String needle){
        int L = needle.length(), n = haystack.length();
        if (L == 0) {
            return 0;
        }

        int pn = 0;
        int l= n-L+1;//需要循环的次数
        while (pn < l) {
            // 找到字符第一个字符与子串第一个字符的位置
            while (pn < l && haystack.charAt(pn) != needle.charAt(0)){
                ++pn;
            }

            // 判断首字符以后与子串比较
            int currLen = 0, pL = 0;
            while (pL < L && pn < n && haystack.charAt(pn) == needle.charAt(pL)) {
                ++pn;
                ++pL;
                ++currLen;
            }

            // 表示有相同的子串
            if (currLen == L) {
                // 返回子串开始的位置
                return pn - L;
            }

            // 如果没有,从出现相同首字符下一个位置开始
            pn = pn - currLen + 1;
        }
        return -1;
    }

 

おすすめ

転載: blog.csdn.net/yu1xue1fei/article/details/114259131