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方法来解决。代码如下:
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;
}
}
实现strStr()方法
本文介绍了一种使用Java实现strStr()方法的方法,该方法返回针在干草堆中首次出现的索引,或者如果针不在干草堆中则返回-1。通过使用substring方法进行字符串匹配,并提供了一个简单的解决方案。
628

被折叠的 条评论
为什么被折叠?



