5. Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"

题解:这道题目的难点在于如何将奇数回文串和偶数回文串归一化处理,即不需要区分奇数偶数回文串来处理;那么首先我们就要来看看偶数回文串特性如habbah,qwerttrew;其实不难发现,就是偶数回文串的中间两个字符肯定是相同的,当然也可能是4个,6个,但至少是2个;而奇数回文串的特性如aba, abbba,其实不难发现中间的字符要么只有1个重复,要么就是3个重复,也有可能就是5个;综上可以看出 无论是奇数还是偶数,中间重复的部分肯定是回文的,那么我们就可他们当成独立的单元来看待:

如 habbah ==ha*ah;qwerttrewq == qwer*rewq; aba == a*a; abbba = a*a;

所以 我题解的核心是将重复的字符作为一个找整体,再去判断重复的字符串左右的字符是否相等;

/*回文串处理方法
万天根
2017/3/22
*/
#include<iostream>
#include<string>
#include<stdlib.h>
#include<time.h>
using namespace std;

class Solution {
public:
	string longestPalindrome(string s) {
		if (s.size() < 2) return s;//当s 为空或者单个字符(也是回文)是直接返回即可
		int  i = 0, Lefti, iRight;//当前中心位置i,回文的最左边Lefti,最有边iRight
		int start = 0, max = 1;//回文的起始位置,回文的最大长度
		int len, length = s.size();//当前字符检测的回文的的长度
		while (i < length) {
			if (length - i < max / 2) break;
			Lefti = iRight = i;

			//程序的核心所在:将重复的字符统一作为回文的中心
			//无论是单个字符为中心,还是奇数偶数个重复的字符为中心,中心肯定是回文的
			//这样的好处是回文字符串是偶数奇数都不用单独去考虑。
			while (s[iRight] == s[iRight + 1]) { iRight++; }

			i = iRight + 1; //下一次寻找循环开始的位置

			//检测除去中心重复字符,左右两端是否相等
			while (iRight < length - 1 && Lefti > 0 && s[iRight + 1] == s[Lefti - 1]) {
				iRight++; Lefti--;
			}

			len = iRight - Lefti + 1;//当前检测到回文串的长度

			if (len > max) { start = Lefti; max = len; }
		}
		return s.substr(start, max);//substr 支付串截取函数
	}
};

int main() {
	srand((unsigned) time(NULL));
	cout << "/*******************Test1***************************" << endl;
	char c;
	int i, x;
	string s = "";
	for ( i = 0; i < 1000; i++) {
		x = rand() % 26;
		c = 'a' + x;
		s += c;
	}
	cout << s << endl;
	Solution test;
	cout << test.longestPalindrome(s) << endl;
	//有趣的测试:10,100,1000,10000,100000个随机的字符串中,最长的回文串的长度,各测试10000次
	cout << "**************************************************/" << endl<<endl;

	int j = 0, k, l;
	int fan = 1;
	int count;
	string ls;
	Solution test2;
	cout << "********************tTest2************************" << endl;
	while (j < 5) {
		fan = fan * 10; count = 0;
		for (k = 0; k < 10000; k++) {
			ls = ""; 
			for (l = 0; l < fan; l++) {
				x = rand() % 26;
				c = 'a' + x;
				ls += c;
			}
			count += test2.longestPalindrome(ls).size();
		}
		double pinjun = double(count)/ 10000;
		cout << fan << "  "<< pinjun << endl;
		j++;
	}
	cout << "***************************************************/" << endl;

	return 0;
}

先看一下leetcode的结果:6ms 还算可以,满足了程序的设定

再看看自己运行的结果


至于10或100或1000.....中随机字符串中的最长回文串的期望,这是个有意思的问题,感觉挺好玩的!但是具体怎么求,感觉好复杂,我还没想出来。


 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值