在 C 程序中打印句子中长度最长的回文词
给定一个句子,找出其中最长的回文
什么是回文?
回文是指即使反转字符串含义仍然相同的词或序列
示例− Nitin,反转字符串后其含义保持不变。
挑战是找出给定句中最长的回文。
如句子:malayalam liemadameil iji
它包含三个回文词,但最长的一个为 − 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
广告
数据结构
网络传输
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP