码迷,mamicode.com
首页 > 其他好文 > 详细

15-2求最大回文的长度

时间:2015-07-17 20:52:05      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

  1. 技术分享
  2. #ifndef PALINDROME_H_
  3. #define PALINDROME_H_
  4. #include<iostream>
  5. #include<string>
  6. int palindrome_longest(char *str,int front,int back);
  7. #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. }
以上就是核心的代码。永远只牺牲一端。不会同时退避两端。












15-2求最大回文的长度

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!