https://leetcode.com/problems/implement-strstr/
这道题用JAVA很简单,因为JAVA有substring和String.equals()函数。
public class Solution {
public int strStr(String haystack, String needle) {
if(needle==null || needle.length()==0) return 0;
if(haystack == null || haystack.length()<needle.length()) return -1;
char first = needle.charAt(0);
for(int i=0; i<=haystack.length()-needle.length(); i++){
if(haystack.charAt(i) == first){
String tmp = haystack.substring(i, i+needle.length());
if(tmp.equals(needle)) return i;
}
}
return -1;
}
}
但是面试肯定不会这么简单。。。。
所以有HashCode和KMP算法,见http://blog.youkuaiyun.com/linhuanmars/article/details/20276833
一会研究一下。。。。。。