字符串中对称子串的最大长度

来源:互联网 发布:刷微信红包软件 编辑:程序博客网 时间:2024/06/06 03:16

1. 描述

输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串“goooogle”, 由于该字符串里最长的对称子字符串是“goooog”, 因此输出 6。

2. 思路

字符串中的每一个开始,向两边扩展,此时可分为两种情况:

(1)对称子串长度是奇数时, 以当前字符为对称轴向两边扩展比较

(2)对称子串长度是偶数时,以当前字符和它右边的字符为对称轴向两边扩展

时间复杂度O(n2);

3. 代码

<pre name="code" class="cpp">#include <iostream>#include <string>using namespace std;int main(){string str;getline(cin,str);int i,j;int len = str.length();int maxlen=0;int maxIndex=0;int tmpLen=0;int left,right;for (i=1;i<len;i++){tmpLen = 1; //对称子串可能为奇数时left = i-1;right = i+1;while(left>=0&&right<len){if (str[left--] == str[right++]){tmpLen += 2;}else{break;}}if (tmpLen > maxlen){maxlen = tmpLen;maxIndex =i;}tmpLen =0;//对称子串可能为偶数时left = i;right = i+1;while(left>=0&&right<len){if (str[left--] == str[right++]){tmpLen += 2;}else{break;}}if (tmpLen > maxlen){maxlen = tmpLen;maxIndex =i;}}cout<<maxlen<<endl;}


0 0