[LeetCode] 28. Implement strStr()



Implement strStr().

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



Solution

The solution to this problem should be quite easy, as we can individually compare the substring of haystack that has the same length as needle.

Once we found the same substring, we return its index i.

Other than that, we only have to cover the situation where the length of haystack or needle is zero.

The code is shown as below.

Java

public class Solution {
    public int strStr(String haystack, String needle) {
        
        if (haystack.length() < needle.length()) {
            return -1;
        } else if (needle.length() == 0) {
            return 0;
        }
        
        for (int i=0;i


你可能感兴趣的:([LeetCode] 28. Implement strStr())