Returns the maximum public string of two strings.

Source: Internet
Author: User

// An interesting question is encountered during the interview today. obtain the maximum public string of the two strings. // The solution is as follows: # include <stdio. h> # include <stdlib. h> # include <string. h> // create a common function char * strsub (char const * pStrSrc, int iStart, int iLen) {if (! PStrSrc | iStart <0) return NULL; int iStrLen = strlen (pStrSrc); char * pStrRes = NULL; if (iLen> = iStrLen-iStart) {pStrRes = (char *) malloc (iStrLen-iStart + 1); if (! PStrRes) return NULL; memset (pStrRes, 0, iStrLen-iStart + 1); strncpy (pStrRes, pStrSrc + iStart, iStrLen-iStart); return pStrRes ;} else {pStrRes = (char *) malloc (iLen + 1); if (! PStrRes) return NULL; memset (pStrRes, 0, iLen + 1); strncpy (pStrRes, pStrSrc + iStart, iLen); return pStrRes;} char * maxComm (char * pStrLeft, char * pStrRight) {if (! PStrLeft |! PStrRight) {return NULL;} char * pStrLess = NULL; char * pStrMore = NULL; char * pStrRes = NULL; int iLeft = strlen (pStrLeft ); int iRight = strlen (pStrRight); int iLess = (iLeft <= iRight )? ILeft: iRight; int I, j; if (iLeft <= iRight) {pStrLess = pStrLeft; pStrMore = pStrRight;} else {pStrLess = pStrRight; pStrMore = pStrLeft ;} char * pSt = NULL; for (I = iLess; I> 0; I --) {for (j = 0; j <= iLess-I; j ++) {pStrRes = strsub (pStrLess, j, I); if (strstr (pStrMore, pStrRes) return pStrRes; free (pStrRes); pStrRes = NULL ;}} return NULL ;} int main (int argc, char ** argv) {char * pStrLeft = "adasdfabc"; char * pStrRight = "asdabcasdf"; puts ("max comm string between two strings "); char * strMaxComm = maxComm (pStrLeft, pStrRight); printf (strMaxComm); puts (""); free (strMaxComm); strMaxComm = NULL; return 0 ;}

 

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.