您好,欢迎访问一九零五行业门户网

打印出给定字符串中既是该字符串前缀又是该字符串后缀的最长部分,在C程序中

给定一个字符串,我们必须检查最长前缀的长度,它也是字符串的后缀,就像有一个字符串“abcab”,所以这里“ab”的长度为2,是最长的子字符串相同的前缀和后缀。
示例input: str[] = { “aabbccdaabbcc” }output: 6input: abdaboutput: 2
如果我们从字符串的开头和结尾开始指针,那么它们会在某个点重叠,所以我们不会这样做,而是从中间断开字符串并开始匹配左右字符串。如果它们相等,则任何一个匹配字符串的返回大小相同,否则尝试两侧的长度较短。
算法int longest(char str[], int n)startstep 1 : declare length as 0 and i as n/2step 2 : if n < 2 then return 1step 3 :loop while till str[i]!='\0' 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 ifend whilereturn lengthstop
示例#include <stdio.h>int longest(char str[], int n){ int length = 0, i = n/2; if( n < 2 ) return 1; while( str[i]!='\0' ){ //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;}
输出如果我们运行上面的程序,它将生成以下输出:
length = 4
以上就是打印出给定字符串中既是该字符串前缀又是该字符串后缀的最长部分,在c程序中的详细内容。
其它类似信息

推荐信息