Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1428808
  • 博文数量: 241
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 2253
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-11 22:27
个人简介

--

文章分类

全部博文(241)

文章存档

2021年(3)

2019年(6)

2018年(1)

2017年(9)

2016年(21)

2015年(50)

2014年(125)

2013年(26)

我的朋友

分类: C/C++

2013-12-25 11:51:24

九度题目:1528
题目描述:

回文串就是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。
回文子串,顾名思义,即字符串中满足回文性质的子串。
给出一个只由小写英文字符a,b,c...x,y,z组成的字符串,请输出其中最长的回文子串的长度。

输入:

输入包含多个测试用例,每组测试用例输入一行由小写英文字符a,b,c...x,y,z组成的字符串,字符串的长度不大于200000。

输出:

对于每组测试用例,输出一个整数,表示该组测试用例的字符串中所包含的的最长回文子串的长度。

样例输入:abab bbbb abba样例输出:3 4 4
思路:从字符串头开始,一位一位往后移动,从字符串尾找到和头相同的位置,之间的位置是否都是对称,如果是则为回文,否则不是。
代码:
     

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;

  4. class Test
  5. {
  6.     public:
  7.         int longHuiData(string str)
  8.         {
  9.             if (str == "")
  10.                 return 0;

  11.             int max = 1;
  12.             int len = str.length();
  13.             int tail ;
  14.             int tmp_tail;
  15.             int head;
  16.             int tmp_head;
  17.             bool equal;

  18.             for (tail = 0; tail < len; tail++)
  19.             {
  20.                 head = len - 1;
  21.                 equal = false;
  22.                 while ( (tail < head) && (str[head] != str[tail]) )
  23.                     head --;
  24.                 
  25.                 tmp_tail = tail;
  26.                 tmp_head = head;
  27.                 while (tmp_tail < tmp_head)
  28.                 {
  29.                     if (str[tmp_tail] == str[tmp_head])
  30.                         equal = true;
  31.                     else
  32.                         break;

  33.                     tmp_tail ++;
  34.                     tmp_head --;
  35.                 }
  36.                 
  37.                 if (equal == true)
  38.                 {
  39.                     if ( (head - tail + 1) > max )
  40.                         max = (head - tail + 1);
  41.                 }
  42.             }            
  43.             
  44.             return max;
  45.         }
  46. };


  47. int main()
  48. {
  49.     cout<<"hello world"<<endl;
  50.     string str;
  51.     int len ;
  52.     class Test my_test;
  53.     while ( cin>>str )
  54.     {
  55.         cout<<str<<endl;
  56.         len = my_test.longHuiData(str);
  57.         cout<<len<<endl;
  58.     }
  59.     return 1;
  60. }

阅读(715) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~