[LeetCode] Implement strstr () to Find a Substring in a Strin

Source: Internet
Author: User

Idea: it is actually matching one by one. There are no highlights in the solution, and I don't want to say anything. Of course, you can also embed IsMatch into StrStr to reduce the overhead of function calling, but the readability may be reduced. 1. If the current character matches, the current character is returned. 2. If the current character does not match, skip one step forward. In fact, similar to the idea of A String Replace Problem, the core reference code is as follows:

bool IsMatch(const char *Str, const char *Pattern)  {      assert(Str && Pattern);      while(*Pattern != '\0')      {          if(*Str++ != *Pattern++)          {              return false;          }      }      return true;  }    char* StrStr(const char *Str, const char *Pattern)  {      assert(Str && Pattern);      while(*Str != '\0')      {          if(IsMatch(Str, Pattern))          {              return const_cast<char *>(Str);          }          else          {              ++Str;          }      }      return NULL;  }  

 

Call the main function as usual:
# Include <stdio. h> # include <assert. h> int main () {const int MAX_N = 50; char Str [MAX_N]; char Pattern [MAX_N]; char * Ans = NULL; while (gets (Str) & gets (Pattern) {Ans = StrStr (Str, Pattern); if (Ans) {puts (Ans );} else {printf ("not a substring \ n ");}}

 

Return 1 ;}

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.