使用C語言程式列印給定字串的最長字首,該字首也是同一字串的字尾。
給定一個字串,我們需要檢查最長字首的長度,該字首也是字串的字尾,例如字串“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
廣告