Title:
Implement strStr ().
Returns the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.
Test Instructions:
Implement strStr ()
Returns the position of the first occurrence of needle in haystack, or 1 if needle is not present in haystack.
Algorithm Analysis:
Method One:
* In Java, there are an API function name indexof (),
* It returns index within this string of the first occurrence of the specifiedsubstring.
Method Two:
* The most native approach
* The idea of solving the problem is, from the first position of the haystack, start judging whether it is a substring individually. If the entire substring matches, then return, otherwise continue to move down the position.
* Note To see haystack the remaining length with needle than enough, not enough words will not be compared.
Method Three:
* Use to see the KMP algorithm, but for an easy difficulty problem, the use of such a brain-based algorithm is not necessary ~ ~
* Interested Reference " thoroughly understand KMP from beginningto end" http://blog.csdn.net/v_july_v/article/details/7041827
* The code is also given below.
AC Code:
Method One:
In Java, there is a API function name indexof (),//IT returns index within this string of the first occurrence of the SP Ecifiedsubstring. public class Solution {public int strStr (String haystack, string needle) { int i; I=haystack.indexof (needle); return i; }}
Method Two:
/** * The most native way to solve the problem is, from the first position of the haystack, start by judging whether it's a substring. If the entire substring matches, then return, otherwise continue to move down the position. * Note To see haystack the remaining length with needle than enough, not enough words will not be compared. */public class solution{public int strStr (String haystack, string needle) { if (Haystack==null | | needle== NULL) return 0; if (needle.length () = = 0) return 0; for (int i=0; i
Method Three:public int strStr (String haystack, string needle) { if (Haystack==null | | needle==null) return 0; int h = haystack. Length (); int n = needle.length (); if (n > H) return-1;if (n = = 0) return 0; int[] Next = getNext (needle); int i = 0; while (i <= h-n) {int success = 1;for (int j = 0; J < N; j + +) {if (Needle.charat (0)! = Haystack.charat (i)) {succes s = 0;i++;break;} else if (Needle.charat (j)! = Haystack.charat (i + j)) {success = 0;i = i + J-next[j-1];break;}} if (success = = 1) return i;} return-1;} Calculate KMP arraypublic int[] GetNext (String needle) {int[] next = new Int[needle.length ()];next[0] = 0; for (int i = 1; I < needle.length (); i++) {int index = next[i-1];while (Index > 0 && needle.charat (index)! = Needle.charat (i)) {index = Next[index -1];} if (Needle.charat (index) = = Needle.charat (i)) {next[i] = next[i-1] + 1;} else {next[i] = 0;}} return next;}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Implement StrStr ()