주어진 문장에서 주어진 문장에서 가장 긴 회문을 찾는 것이 과제입니다.
회문이란 무엇입니까?
회문은 문자열을 반대로 해도 의미가 동일하게 유지되는 단어 또는 시퀀스입니다.
예 − Nitin, 문자열을 반대로 해도 의미는 동일하게 유지됩니다.
주어진 문장에서 가장 긴 회문을 찾는 것이 과제입니다.
같은 문장은 다음과 같습니다:malayalamliemadameil iji
3개의 회문 단어가 포함되어 있지만 가장 긴 단어는 -liemadameil
알고리즘
START STEP 1 -> Declare start variables I, j, k, l, max to 0, index to -1, check to 0, count to 0 Step 2 -> Loop For i to 0 and i<strlen(str) and i++ Set max =0, k =i and j=i+1 Loop While str[j]!=' ' and str[j]!='\0' Increment j by 1 End While Set l=j-1 IF str[k]!=' ' and str[k]!='\0' Loop While k<=1 If str[k]==str[l] Increment max by 1 If count<=max Set index=i and count = max End If End IF Else Set max = 0, count = -1 Break End Else Increment k and I by 1 End Loop While End If Set i=j Step 3 -> End Loop For Step 4 -> Loop For i = index and i!=-1 && str[i]!=' ' && str[i]!='\0' and i++ Print str[i] Step 5 -> End Loop For STOP
예
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[]) {
char str[] = {"malayalam liemadameil iji"};
int i, k, l, j, max =0, index = -1, check = 0, count = 0;
for(i=0; i<strlen(str); i++) {
max = 0;
k = i;
j = i+1;
while(str[j]!=' ' && str[j]!='\0'){
j++;
}
l = j-1;
if(str[k]!=' ' && str[k]!='\0') {
while(k<=l) {
if (str[k]==str[l]) {
max++;
if(count<=max) {
index = i;
count = max;
}
} else {
max = 0;
count = -1;
break;
}
k++;
l--;
}
}
i = j;
}
for (i = index; i!=-1 && str[i]!=' ' && str[i]!='\0'; i++) {
printf("%c", str[i]);
}
return 0;
} 출력
위의 프로그램을 실행하면 다음과 같은 출력이 생성됩니다.
liemadameil