首页 > 后端开发 > C++ > 正文

在C程序中,将句子中最长的回文单词打印出来

WBOY
发布: 2023-09-04 22:57:07
转载
760 人浏览过

在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]!=&#39; &#39; and str[j]!=&#39;\0&#39;
      Increment j by 1
   End While
   Set l=j-1
   IF str[k]!=&#39; &#39; and str[k]!=&#39;\0&#39;
      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]!=&#39; &#39; && str[i]!=&#39;\0&#39; 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]!=&#39; &#39; && str[j]!=&#39;\0&#39;){
         j++;
      }
      l = j-1;
      if(str[k]!=&#39; &#39; && str[k]!=&#39;\0&#39;) {
         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]!=&#39; &#39; && str[i]!=&#39;\0&#39;; i++) {
      printf("%c", str[i]);
   }
   return 0;
}
登录后复制

输出

如果我们运行上面的程序,它将生成以下输出。

liemadameil
登录后复制

以上是在C程序中,将句子中最长的回文单词打印出来的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!