LeetCode 28 Implement strStr()

来源:互联网 发布:天天酷跑ios清除数据 编辑:程序博客网 时间:2024/06/08 15:58

Implement strStr().

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

对于这个题目,JAVA封装的有现成的方法,一句话搞定。

public int strStr(String haystack, String needle) {return haystack.indexOf(needle);}
可是呢,我们还是多写点儿把,不直接调用String.indexOf来实现。代码如下:

public int strStr(String haystack, String needle) {if (needle.isEmpty()) return 0;int len1 = haystack.length();int len2 = needle.length();for (int i = 0; i <= len1 - len2; i++) {for (int j = 0; j < len2; j++) {if (haystack.charAt(i + j) != needle.charAt(j)) break;if (j == len2 - 1) return i;}}return -1;}


另外,还可以是使用kmp算法、Boyer-Mooer 算法和Rabin-Karp 算法,时间复杂度为O(m+n)。

0 0