[C + +] Implement StrStr ()

Source: Internet
Author: User

Implement strStr ().

Return the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.

Example 1:

Input:haystack = "Hello", needle = "ll" Output:2

Example 2:

Input:haystack = "AAAAA", needle = "BBA" Output: 1

The STRSTR () function returns a matching first character index.

Conventional matching algorithms can be used, brute force algorithm

Traverse Haystack to m-n+1 while traversing needle from 0 to N,while to determine whether two string corresponding characters are equal.

classSolution { Public:    intSTRSTR (stringHaystackstringneedle) {        intm = Haystack.size (), n =needle.size (); if(n = =0)            return 0;  for(inti =0; I < M-n +1; i++) {            intj =0;  while(Haystack[i + j] = =Needle[j]) {J++; if(J = =N)returni; } J++; }        return-1; }};//6 Ms

[C + +] Implement StrStr ()

Related Article

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.