implement strStr()这就是第一次online coding遇到的题,竟然是leetcode原题,还是easy,偏偏一直没写过==,真该掌嘴。
思路简单,从0开始扫0+needle.length()的haystack的substring,match就return index,找不到就返回-1。 需要注意两个String “” 和 “” 要返回0。
这道题的时间复杂度比较坑,我再leetcode的discuss里面和别人讨论了很久,具体的连接在这里。我这样写会让时间复杂度变成O(N*M*M)。
public int strStr(String haystack, String needle) {
if(haystack == null || needle == null || needle.length() > haystack.length()) return -1;
if(haystack.length() == 0 && needle.length() == 0) return 0;
int needleLen = needle.length();
int haystackLen = haystack.length();
int i = 0;
while(i < haystackLen) {
if(i + needleLen > haystackLen) return -1; // check if outOfBoundry
if(haystack.substring(i, i + needleLen).equals(needle)) return i;
i++;
}
return -1;
}
这是不用substring写的,复杂度O(M*N)
public int strStr(String haystack, String needle) {
if(haystack == null || needle == null) return -1;
int hayLen = haystack.length();
int needLen = needle.length();
if(needLen > hayLen) return -1;
if(needle.equals("")) return 0;
int cnt = 0;
int i = 0;
while((i + cnt) < hayLen && cnt < needLen){ // 两个条件避免溢出
if(needle.charAt(cnt) == haystack.charAt(i+cnt)) cnt++; //顺序比较
else {
i++; //找到不匹配从下一个haystack位置开始
cnt = 0;
}
}
if(cnt==needLen) return i;
return -1;
}
再有O(N)的方法就要用KMP算法了,看了几篇文章发现思路好懂,大致思路在找到不匹配的时候haystack位置不是增加1,而是增加另一个数,这个数由needle的特点决定,包括needle里面的char对称部分。code不好写,写出来没这个简便易懂,我就不误人子弟了,大家有兴趣自己搜搜吧。