Leetcode 28. Implement strStr () string

Source: Internet
Author: User

Implement StrStr ()

Implement strStr ().

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


find the position that matches the first needle in the haystack. If not found, returns-1.

The code is as follows:

Class solution {public:    int strstr (string haystack, string  needle)  {        if (haystack.size ()  == 0  && needle.size ()  == 0)              return 0;        if (Needle.size ()  == 0)             return 0;         if (Haystack.size ()  < needle.size ())              return -1;        for (int  i = 0;i < haystack.size ()  - needle.size ()  + 1;i++)          {             bool flag = true;            if (Needle[0] == haystack[i])             {                 int j = 0;                 for (; j <  Needle.size (); j + +)                  {                     if (Needle[j] != haystack[i+j])                      {                          Flag = false;                         break;                     }                                          }       &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;IF (flag)                      return i;             }        }         return -1;    }};

2016-08-11 01:02:49

This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1836727

Leetcode 28. Implement strStr () string

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.