leetcode28. 实现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() 定义相符。

思路:水题一道,直接调用原有的内置 indexOf 函数判断即可。

class Solution {
    public int strStr(String haystack, String needle) {
		return haystack.indexOf(needle);
	}
}

但是为了追求更高还是看看这个函数的源码吧,在 eclipse 中选中 indexOf 函数,按 F3,即可进入相关文档,然后在一直找具体的源码。

 /**
     * Code shared by String and StringBuffer to do searches. The
     * source is the character array being searched, and the target
     * is the string being searched for.
     *
     * @param   source       the characters being searched.
     * @param   sourceOffset offset of the source string.
     * @param   sourceCount  count of the source string.
     * @param   target       the characters being searched for.
     * @param   targetOffset offset of the target string.
     * @param   targetCount  count of the target string.
     * @param   fromIndex    the index to begin searching from.
     */
    static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
        }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
        if (targetCount == 0) {
            return fromIndex;
        }

        char first = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

看了代码后,看了很久,感觉很牛逼,将字符串转换为字符数组来进行查找。

传进七个参数,char[] source:源字符串,int sourceOffset:类似于下标或者指针吧,int sourceCount:原字符串的长度,

char[] target:目标字符串,int targetOffset:目标字符串的指针,int targetCount:目标字符串的长度,fromIndex:查找的起始位置。

首先将目标函数为空,和起始位置大于原字符数组的长度,防止数组越界和误传寻找的起始数组下标为负数的情况,也就是考虑了数组的上限和下限类似的意思。

然后开始找出 target 的第一位在源字符数组的第一个位置,这里它使用了两个数组长度相减来确定寻找的第一个字符的位置,减少了查找的时间,和后面的找到第一个字符后,再继续查找其他字符,也是用目标字符的长度确定继续查找的范围,继而缩短查找时间。

 

你可能感兴趣的:(数据结构,蓝桥杯-java,java)