28. Implement strStr() - Easy

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().

用substring()来判断

注意:Java 7中,string.substring()的时间复杂度是O(n),n为子串长度

time: O(mn), space: O(1)  -- m: needle length, n: haystack length

class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack == null || needle == null) return -1;
        if(haystack.length() < needle.length()) return -1;
        if(needle.length() == 0) return 0;
        
        int m = needle.length();
        for(int i = 0; i <= haystack.length() - m; i++) {
            if(haystack.substring(i, i + m).equals(needle))
                return i;
        }
        return -1;
    }
}

猜你喜欢

转载自www.cnblogs.com/fatttcat/p/10133131.html
今日推荐