LeetCode, leetcodeoj

Source: Internet
Author: User

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.

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.