給定一個字符串,我們必須檢查最長前綴的長度,它也是字符串的后綴,就像有一個字符串“abcab”,所以這里“ab”的長度為2,是最長的子字符串相同的前綴和后綴。
示例
Input: str[] = { “aabbccdaabbcc” }
Output: 6
Input: abdab
Output: 2
登錄后復制
如果我們從字符串的開頭和結尾開始指針,那么它們會在某個點重疊,所以我們不會這樣做,而是從中間斷開字符串并開始匹配左右字符串。如果它們相等,則任何一個匹配字符串的返回大小相同,否則嘗試兩側的長度較短。
算法
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]!='\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 IF
END WHILE
RETURN length
STOP
登錄后復制
示例
#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程序中的詳細內容,更多請關注www.xfxf.net其它相關文章!






