LeetCode, leetcodeoj
Description:
Implement strStr ().
Returns the index of the first occurrence of needle in haystack, or-1 if needle is not part of haystack.
It is actually a function to find the starting position of the substring.
Ideas:
This article uses a traditional solution, which involves two-layer traversal. For the character string haystack, move it one by one to determine whether the value of haystack [I... needle. Length] is equal to the value of needle.
The faster algorithm is KMP. The two articles are very clear:
Http://blog.csdn.net/v_july_v/article/details/7041827
Http://www.ruanyifeng.com/blog/2013/05/Knuth-Morris-Pratt_algorithm.html
Implementation Code:
public class Solution { public int StrStr(string haystack, string needle) { var i = 0; while(i < haystack.Length - needle.Length + 1){ var k = i; while(k < haystack.Length - needle.Length + 1){var s = haystack.Substring(k, needle.Length); if(s == needle){ return k; }k++; }i++; } return -1; }}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.