15-2求最大回文的长度


  1. #ifndef PALINDROME_H_
  2. #define PALINDROME_H_
  3. #include<iostream>
  4. #include<string>
  5. int palindrome_longest(char *str,int front,int back);
  6. #endif
  1. #include"Palindrome.h"
  2. #define Max(a,b) a>b? a:b
  3. int palindrome_longest(char *str,int front,int back){
  4. int pali_count=0;
  5. if(front==back)
  6. return pali_count+1;
  7. if(str[front]==str[back]){
  8. pali_count=palindrome_longest(str,front+1,back-1)+1;
  9. }else{
  10. pali_count=Max(palindrome_longest(str,front+1,back),palindrome_longest(str,front,back-1));
  11. }
  12. return pali_count;
  13. }
  1. #include "LongPath.h"
  2. #include "Palindrome.h"
  3. int main(){
  4. char *str="civic";
  5. char *str0="racecar";
  6. char *str1="character";
  7. std::cout<<palindrome_longest(str,0,4)<<std::endl;
  8. std::cout<<palindrome_longest(str0,0,6)<<std::endl;
  9. std::cout<<palindrome_longest(str1,0,8)<<std::endl

在上面的算法中,我们采用了求最长公共子序列一样的算法,也就是《算法导论》第三版 15-4节。
其思想很值得借鉴。对于处理这些“非正规”的子符串问题很有启发性,对于最长公共子序列,并
不是我们以前志熟悉的那种连续性的最长公共子序列,而是求不要求连续性的公共子序列,于是知
我们不能从两个子序列都开始缩进或者退避。


这就是这些问题的特点。
对于这个问题的回文是,我们采用类似的思想,如果相等,那好,他们回文的长度加1,如果不相等,那
只有其中的一端要牺牲一下啦,它要退回一个字符,然后求这两个的最长的那个就行了。
  1. if(str[front]==str[back]){
  2. pali_count=palindrome_longest(str,front+1,back-1)+1;
  3. }else{
  4. pali_count=Max(palindrome_longest(str,front+1,back),palindrome_longest(str,front,back-1));
  5. }
以上就是核心的代码。永远只牺牲一端。不会同时退避两端。












原文地址:https://www.cnblogs.com/yml435/p/4655525.html