Home > Backend Development > C++ > Print out the longest part of a given string that is both a prefix and a suffix of the string, in a C program

Print out the longest part of a given string that is both a prefix and a suffix of the string, in a C program

WBOY
Release: 2023-09-23 20:33:11
forward
920 people have browsed it

Print out the longest part of a given string that is both a prefix and a suffix of the string, in a C program

给定一个字符串,我们必须检查最长前缀的长度,它也是字符串的后缀,就像有一个字符串“abcab”,所以这里“ab”的长度为2,是最长的子字符串相同的前缀和后缀。

示例

Input: str[] = { “aabbccdaabbcc” }
Output: 6
Input: abdab
Output: 2
Copy after login

如果我们从字符串的开头和结尾开始指针,那么它们会在某个点重叠,所以我们不会这样做,而是从中间断开字符串并开始匹配左右字符串。如果它们相等,则任何一个匹配字符串的返回大小相同,否则尝试两侧的长度较短。

算法

int longest(char str[], int n)
START
STEP 1 : DECLARE length AS 0 AND i AS n/2
STEP 2 : IF n < 2 THEN
   RETURN 1
STEP 3 :LOOP WHILE TILL str[i]!=&#39;\0&#39;
   IF str[i] == str[length] THEN,
      INCREMENT length BY 1
      INCREMENT i BY 1
   ELSE
      IF length == 0 THEN,
         INCREMENT i BY 1
      ELSE
         DECREMENT length BY 1
      END IF
   END IF
END WHILE
RETURN length
STOP
Copy after login

示例

#include <stdio.h>
int longest(char str[], int n){
   int length = 0, i = n/2;
   if( n < 2 )
      return 1;
   while( str[i]!=&#39;\0&#39; ){
      //When we find the character like prefix in suffix,
      //we will move the length and i to count the length of the similar prefix and suffix
      if (str[i] == str[length]){
         ++length;
         ++i;
      } else //When prefix and suffix not equal{
         if(length == 0)
            ++i;
         else
            --length;
      }
   }
   return length;
}
int main(int argc, char const *argv[]){
   char str[] = {"abccmmabcc"};
   int n = sizeof(str)/sizeof(str[0]);
   int length = longest(str, n);
   printf("Length = %d", length);
   return 0;
}
Copy after login

输出

如果我们运行上面的程序,它将生成以下输出:

Length = 4
Copy after login

The above is the detailed content of Print out the longest part of a given string that is both a prefix and a suffix of the string, in a C program. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template