题目
我的思路属于暴力解法:
public int strStr(String haystack, String needle) {
if(needle.equals(""))return 0;
if(haystack.length() < needle.length()) return -1;
int hl = haystack.length();
int nl = needle.length();
if(hl == nl) return haystack.equals(needle) ? 0:-1;
for(int i = 0; i+nl-1< hl;i++){
String temp = haystack.substring(i,i+needle.length());
if(needle.equals(temp)){
return i;
}
}
return -1;
}
每一次对第一个数组进行subString()长度就为第二个数组的长度即可。挨个比对。
时间复杂度是O(mn)
空间复杂度是O(1)
大佬解决方法KMP算法我是一时半会没理解懂5555
还有著名的字符串匹配算法 KMP,BM,Horspool
作者:labuladong KMP算法