搜索
首页后端开发C++C程序查找形成回文的最小插入次数

C程序查找形成回文的最小插入次数

回文是一个与其反转相等的字符串。给定一个字符串,我们需要找到使该字符串成为回文所需的最小插入任意字符的数量。我们将看到三种方法:首先是递归方法,然后我们将记忆化这个解决方案,最后,我们将实现动态规划方法。

递归方法

示例

#include <stdio.h> // library for input and output
#include <limits.h> // library to get the integer limits 
#include <string.h> // library for strings 
// function to find the minimum of two number 
// as it is not present in the c language 
int findMin(int a, int b){ 
   if(a < b){
      return a;
   } else{
      return b;
   }
}
// creating the function to find the required answer we will make recursive calls to it 
int findAns(char str[], int start, int end){
   // base condition
   if (start > end){
      return INT_MAX;
   }
   else if(start == end){
      return 0;
   }
   else if (start == end - 1){
      if(str[start] == str[end]){
         return 0;
      }
      else return 1;
   }	
   // check if both start and end characters are the same make callson the basis of that 
   if(str[start] == str[end]){
      return findAns(str,start+1, end-1);
   } else{
      return 1+ findMin(findAns(str,start,end-1), findAns(str,start+1,end));
   }
}
// main function 
int main(){
   char str[] = "thisisthestring"; // given string
   printf("The minimum number of insertions required to form the palindrome is: %d", findAns(str,0,strlen(str)-1));
   return 0;
}

输出

The minimum number of insertions required to form the palindrome is: 8

时间和空间复杂度

以上代码的时间复杂度为O(2^N),因为我们对每个插入都进行选择,其中N是给定字符串的大小。

上述代码的空间复杂度为O(N),即在递归调用中使用。

记忆方法

例子

#include <stdio.h> // library for input and output
#include <limits.h> // library to get the integer limits 
#include <string.h> // library for strings 

int memo[1005][1005]; // array to store the recursion results 
// function to find the minimum of two number 
// as it is not present in the c language 
int findMin(int a, int b){ 
   if(a < b){
      return a;
   } else{
      return b;
   }
}
// creating the function to find the required answer we will make recursive calls to it 
int findAns(char str[], int start, int end){
   // base condition
   if (start > end){
      return INT_MAX;
   }
   else if(start == end){
      return 0;
   }
   else if (start == end - 1){
      if(str[start] == str[end]){
         return 0;
      }
      else return 1;
   }
   // if already have the result 
   if(memo[start][end] != -1){
      return memo[start][end];
   }	
   // check if both start and end characters are same make calls on basis of that 
    if(str[start] == str[end]){
      memo[start][end] =  findAns(str,start+1, end-1);
   } else{
        memo[start][end] =  1+ findMin(findAns(str,start,end-1), findAns(str,start+1,end));
   }
   return memo[start][end];
}
int main(){
   char str[] = "thisisthestring"; // given string	
   //Initializing the memo array 
   memset(memo,-1,sizeof(memo));
   printf("The minimum number of insertions required to form the palindrome is: %d", findAns(str,0,strlen(str)-1));	
   return 0;
}

输出

The minimum number of insertions required to form the palindrome is: 8

时间和空间复杂度

上述代码的时间复杂度为O(N^2),因为我们存储了已经计算过的结果。

上述代码的空间复杂度为O(N^2),因为我们在这里使用了额外的空间。

动态规划方法

示例

#include <stdio.h> // library for input and output
#include <limits.h> // library to get the integer limits 
#include <string.h> // library for strings 
    
// function to find the minimum of two number 
// as it is not present in the c language 
int findMin(int a, int b){ 
   if(a < b){
      return a;
   } else{
      return b;
   }
}
// creating a function to find the required answer 
int findAns(char str[], int len){
   // creating the table and initialzing it 
   int memo[1005][1005]; 
   memset(memo,0,sizeof(memo));	
   // filling the table by traversing over the string 
   for (int i = 1; i < len; i++){
      for (int start= 0, end = i; end < len; start++, end++){
         if(str[start] == str[end]){
            memo[start][end] = memo[start+1][end-1];
         } else{
              memo[start][end] = 1 + findMin(memo[start][end-1], memo[start+1][end]);
         }
      }
   }
   // return the minimum numbers of interstion required for the complete string 
      return memo[0][len-1];
}
int main(){
   char str[] = "thisisthestring"; // given string	
   // calling to the function 
   printf("The minimum number of insertions required to form the palindrome is: %d", findAns(str, strlen(str)));	
   return 0;
}

输出

The minimum number of insertions required to form the palindrome is: 8

时间和空间复杂度

上述代码的时间复杂度为O(N^2),因为我们在这里使用了嵌套的for循环。

上述代码的空间复杂度为O(N^2),因为我们在这里使用了额外的空间。

结论

在本教程中,我们实现了三种方法来找到使给定字符串成为回文所需的最小插入次数。我们实现了递归方法,然后进行了记忆化处理。最后,我们实现了表格法或动态规划法。

以上是C程序查找形成回文的最小插入次数的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
C社区:资源,支持和发展C社区:资源,支持和发展Apr 13, 2025 am 12:01 AM

C 学习者和开发者可以从StackOverflow、Reddit的r/cpp社区、Coursera和edX的课程、GitHub上的开源项目、专业咨询服务以及CppCon等会议中获得资源和支持。1.StackOverflow提供技术问题的解答;2.Reddit的r/cpp社区分享最新资讯;3.Coursera和edX提供正式的C 课程;4.GitHub上的开源项目如LLVM和Boost提升技能;5.专业咨询服务如JetBrains和Perforce提供技术支持;6.CppCon等会议有助于职业

c#vs. c:每种语言都擅长c#vs. c:每种语言都擅长Apr 12, 2025 am 12:08 AM

C#适合需要高开发效率和跨平台支持的项目,而C 适用于需要高性能和底层控制的应用。1)C#简化开发,提供垃圾回收和丰富类库,适合企业级应用。2)C 允许直接内存操作,适用于游戏开发和高性能计算。

继续使用C:耐力的原因继续使用C:耐力的原因Apr 11, 2025 am 12:02 AM

C 持续使用的理由包括其高性能、广泛应用和不断演进的特性。1)高效性能:通过直接操作内存和硬件,C 在系统编程和高性能计算中表现出色。2)广泛应用:在游戏开发、嵌入式系统等领域大放异彩。3)不断演进:自1983年发布以来,C 持续增加新特性,保持其竞争力。

C和XML的未来:新兴趋势和技术C和XML的未来:新兴趋势和技术Apr 10, 2025 am 09:28 AM

C 和XML的未来发展趋势分别为:1)C 将通过C 20和C 23标准引入模块、概念和协程等新特性,提升编程效率和安全性;2)XML将继续在数据交换和配置文件中占据重要地位,但会面临JSON和YAML的挑战,并朝着更简洁和易解析的方向发展,如XMLSchema1.1和XPath3.1的改进。

现代C设计模式:构建可扩展和可维护的软件现代C设计模式:构建可扩展和可维护的软件Apr 09, 2025 am 12:06 AM

现代C 设计模式利用C 11及以后的新特性实现,帮助构建更灵活、高效的软件。1)使用lambda表达式和std::function简化观察者模式。2)通过移动语义和完美转发优化性能。3)智能指针确保类型安全和资源管理。

C多线程和并发:掌握并行编程C多线程和并发:掌握并行编程Apr 08, 2025 am 12:10 AM

C 多线程和并发编程的核心概念包括线程的创建与管理、同步与互斥、条件变量、线程池、异步编程、常见错误与调试技巧以及性能优化与最佳实践。1)创建线程使用std::thread类,示例展示了如何创建并等待线程完成。2)同步与互斥使用std::mutex和std::lock_guard保护共享资源,避免数据竞争。3)条件变量通过std::condition_variable实现线程间的通信和同步。4)线程池示例展示了如何使用ThreadPool类并行处理任务,提高效率。5)异步编程使用std::as

C深度潜水:掌握记忆管理,指针和模板C深度潜水:掌握记忆管理,指针和模板Apr 07, 2025 am 12:11 AM

C 的内存管理、指针和模板是核心特性。1.内存管理通过new和delete手动分配和释放内存,需注意堆和栈的区别。2.指针允许直接操作内存地址,使用需谨慎,智能指针可简化管理。3.模板实现泛型编程,提高代码重用性和灵活性,需理解类型推导和特化。

C和系统编程:低级控制和硬件交互C和系统编程:低级控制和硬件交互Apr 06, 2025 am 12:06 AM

C 适合系统编程和硬件交互,因为它提供了接近硬件的控制能力和面向对象编程的强大特性。1)C 通过指针、内存管理和位操作等低级特性,实现高效的系统级操作。2)硬件交互通过设备驱动程序实现,C 可以编写这些驱动程序,处理与硬件设备的通信。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境