28. Implement strStr()

2019/11/12 Leetcode

28. Implement strStr()

Tags: ‘Two Pointers’, ‘String’

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

Solution

方法1 Naive $O(M(N-M)) O(1)$

public int strStr(String haystack, String needle) {
    // Naive
    if (haystack == null || needle == null) return -1;
    int N = haystack.length();
    int M = needle.length();
    if (M == 0) return 0;
    
    for (int i = 0; i <= N - M; i++) {
        int j;
        for (j = 0; j < M; j++) {
            if (haystack.charAt(i + j) != needle.charAt(j)) {
                break; 
            }    
        }
        
        if (j == M) {
            return i;
        } 
    }
    return -1;
}

方法2 KMP (Knuth Morris Pratt) Pattern Searching $O(n)$ 考到的概率很小


Search

    Table of Contents