题目:
输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串“google”,由于该字符串里最长的对称子字符串是“goog”,因此输出 4。
解题思路:
方法一:判断字符串的每一个子串,若是对称的,则求出它的长度即可。这种办法对每一个子串,从两头向中间判断是不是子串。总的时间复杂度为O(n^3),
下面给出时间复杂度是O(n^2)的思路。
方法二:与方法一正好相反,字符串中的每一个开始,向两边扩展,此时可分为两种情况:
(1)对称子串长度是奇数时, 以当前字符为对称轴向两边扩展比较
(2)对称子串长度是偶数时,以当前字符和它右边的字符为对称轴向两边扩展
实现代码:
#include <iostream> #include <cstring> int get_maxlen(const char *str){ const char * current=str; int max_len=1; int temp_len=1; while(*current){ //奇数长度对称字符串处理 const char * begin=current-1; const char * end=current+1; while(begin>=str && *end && *begin==*end){ begin--; end++; } temp_len=end-begin-1; if(temp_len>max_len) max_len=temp_len; //偶数长度对称字符串处理 begin=current; end=current+1; while(begin>=str && *end && *begin==*end){ begin--; end++; } temp_len=end-begin-1; if(temp_len>max_len) max_len=temp_len; current++; } return max_len; } int main() { const char * str="googleaelg"; int ret = get_maxlen(str); std::cout<<ret<<std::endl; return 0; }
实际上,求字符串最长对称字串即为找最长回文字串,在这篇博文中提到了两种解题思路,第一种复杂度为O(n),详情请查看:http://www.cnblogs.com/mickole/articles/3578298.html