Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解题思路:
解题想法是,从haystack的第一个位置,开始逐个判断是不是子串。如果整个子串都匹配了,那么就返回,否则继续往下挪位置。
Complexity: O(mn) , m is the length of haystack, n is the length of needle
还有一个KMP解法,算法复杂度很好,但目前没研究。以后再说。
Java code:
public int strStr(String haystack, String needle) { if( haystack == null || needle == null || needle.length() == 0 ) { return 0; } for(int i = 0; i < haystack.length(); i++) { if(i + needle.length() > haystack.length()) { return -1; } int m = i; for(int j = 0; j < needle.length(); j++) { if(needle.charAt(j) == haystack.charAt(m)){ if(j == needle.length()-1) { return i; } m++; }else { break; } } } return -1; }
Reference:
1. http://www.programcreek.com/2012/12/leetcode-implement-strstr-java/
2. http://jakeboxer.com/blog/2009/12/13/the-knuth-morris-pratt-algorithm-in-my-own-words/
3. http://www.cnblogs.com/springfor/p/3896469.html