问题链接:https://oj.leetcode.com/submissions/detail/17799169/
问题描述:Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
问题API: public int strStr(String haystack, String needle)
问题分析:其实网上有很多很牛逼的算法,比较常见的有KMP。但实际上我个人认为除非你是想秀操作,否则brute force就好,毕竟普通人类是不太可能在没有背过KMP算法的情况下临场构思出来。那些都是论文级别的算法,写出来就告诉面试官你是在背答案。
Brute force的算法实际也很简单,就是匹配haystack[i, i + 1, i + 2... i + needle.length() - 1] 和 needle[0, 1, 2... needle.length() - 1], 匹配不下去就i++,直到第一个匹配完整的就返回。
代码如下:
public int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0)
return 0;
if(haystack == null)
return -1;
for(int i = 0; i <= haystack.length() - needle.length(); i++){
boolean found = true;
for(int j = 0; j < needle.length(); j++){
if(haystack.charAt(i + j) != needle.charAt(j)){
found = false;
break;
}
}
if(found)return i;
}
return -1;
}