Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Analysis:这道题在leetcode String分类里算简单的。是因为暴力法很简单易懂。更高级的有Rabin-Karp algorithm, KMP algorithm 和 Boyer0 Moore algorigthm。以上都是出现在高级算法设计课的。暂时达不到那个高度。
Solution:
1: public static int strStr(String haystack, String needle)
2: {
3: int hlen=haystack.length();
4: int nlen=needle.length();
5: if(haystack==null || needle==null || nlen<hlen)
6: return -1;
7: boolean isSub=true;
8: for(int i=0;i<hlen-nlen;i++)
9: {
10: isSub=true;
11: for(int j=0;j<nlen;j++)
12: {
13: if(haystack.charAt(i+j)!=needle.charAt(j))
14: {
15: isSub=false;
16: break;
17: }
18: }
19: if(isSub)
20: return i;
21: }
22: return -1;
23: }
没有评论:
发表评论