"028-implement strStr () (Implement STRSTR () function)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
Implement strStr ().
Returns the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.
Main Topic
Implement the STRSTR () function to determine where a string appears in another string. If it does not match, return-1.
Thinking of solving problems
Implementation using the KMP algorithm
Code Implementation
Algorithm implementation class
public class Solution {publicintSTRSTR (String haystack, string needle) {if(haystack = = NULL | | needle = = NULL) {return-1; }if(Needle.length() > Haystack.length()) {return-1; }if("". Equals (haystack)) {if("". Equals (needle)) {return 0; }Else{return-1; } }Else{if("". Equals (needle)) {return 0; } }returnKmpindex (haystack, needle); } privateintKmpindex (String haystack, string needle) {inti =0;intj =0;int[]Next=Next(needle); while(I < haystack.length() && J < Needle.length()) {if(j = =-1|| Haystack.charat (i) = = Needle.charat (j)) {++i; ++j; }Else{j =Next[j]; } }if(j = = needle.length()) {returnI-j; }Else{return-1; }} Privateint[]Next(String needle) {int[]Next= newint[Needle.length()];Next[0] = -1;inti =0;intj =-1;intK = needle.length() -1; while(I < k) {if(j = =-1|| Needle.charat (i) = = Needle.charat (j)) {++i; ++j;if(Needle.charat (i)! = Needle.charat (j)) {Next[I] = j; }Else{Next[I] =Next[j]; } }Else{j =Next[j]; } }return Next; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47052669"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "028-implement StrStr () (Implement STRSTR () function)"