Implement strStr()

Implement strStr().

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

这道题目实际上就是让我们实现java中的indexOf方法,有关字符串匹配的问题,有一个时间复杂为线性时间的算法-KMP,这里我们使用java中的substring方法来解决。代码如下:

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

猜你喜欢

转载自kickcode.iteye.com/blog/2274173