"Leetcode KMP Algorithm Implementation" Implement STRSTR () __ algorithm

Source: Internet
Author: User

Topic:

Implement strStr ().

Returns A pointer to the first occurrence of needle in haystack, or null if needle are not part of haystack.

Parse: Implements the Strstr () method, given the string haystack and needle, to return the position of the first occurrence of needle in haystack. The general solution to the problem is very simple, and the substring starting with each character in Haystack is compared to the needle, and if equal returns the substring at the beginning of the character. The time complexity of the algorithm is O (m*n), M is the length of haystack, and N is the length of needle.

I use the KMP algorithm to implement the string alignment problem, first for the pattern string needle to find its next array, and then traverse the haystack string.

The Java AC code is as follows:

public class Solution {public String strStr (String haystack, string needle) {if (haystack = null | | needle = NULL)
		{return null;

		} int[] Next = getNext (needle);
		int PS = 0, PH = pS, PN = 0;
			while (PS + needle.length () <= haystack.length ()) {if (PN = = Needle.length ()) {return haystack.substring (PS);
				} else if (Haystack.charat (PS + pH) = = Needle.charat (PN)) {ph++;
			pn++;
				} else if (NEXT[PN + 1] = = 0) {PH = PN = 0;
			ps++;
				} else {PH-= (PN-NEXT[PN]);
				PS + = (PN-NEXT[PN]);
			PN = NEXT[PN];
	}} return null;
		} public static int[] GetNext (String needle) {int[] next = new Int[needle.length () + 1];
		Next[0] =-1;
		Needle = ' $ ' + needle; for (int i = 1; i < needle.length (); i++) {if (next[i-1] = = 0) {Next[i] = Needle.charat (i) = = Needle.charat ( 1)?
			1:0;
				} else {int before = next[i-1]; while (Before! =-1) {if (Needle.charat (before + 1) = = Needle.charat (i)) {Next[i]= before + 1;
					Break
					} else {before = Next[before];
	}}}} return to Next; }
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.