Leetcode-28. 实现 strStr()

222 阅读1分钟

实现 strStr() 函数。

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

示例 1:

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

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

链接:leetcode-cn.com/problems/im…

暴力解法: 从haystack的第一个字符开始和needle比较
相等:各向后移一个
不相等:haystack向后移一位。
之后重复以上操作。

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

        while (start + needle.length() <= haystack.length()) {
            if (haystack.charAt(start + n) == needle.charAt(n)) {
                if (n == needle.length() - 1) {
                    return start;
                }
                n++;
            } else {
                start++;
                n = 0;
            }
        }
        return -1;


    }

sunday解法: 链接: leetcode-cn.com/problems/im…
借助一个偏移表,保存每个字母最后一位到末尾的长度。

    public int strStr(String haystack, String needle) {
        if (needle.isEmpty()) {
            return 0;
        }
        int hlength = haystack.length();
        int nlength = needle.length();

        int[] temp = new int[26];
        for (int i = 0; i < nlength; i++) {
            temp[needle.charAt(i) - 'a'] = nlength - i;
        }
        int index = 0;
        while (index + nlength <= hlength) {
            if (haystack.substring(index, index + nlength).equals(needle)) {
                return index;
            } else {
                if (index + nlength == hlength) {
                    return -1;
                }
                if (temp[haystack.charAt(index + nlength) - 'a'] != 0) {
                    index += temp[haystack.charAt(index + nlength) - 'a'];
                } else {
                    index += nlength + 1;
                }
            }

        }
        return -1;
    }