leetcode 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, and there exists one unique longest palindromic substring.


class Solution {
	bool is_palindrome(string&s, int startindex, int endindex)
	{
		while (endindex >= startindex&&s[startindex] == s[endindex])
		{
			startindex++;
			endindex--;
		}
		return startindex > endindex;
	}
public:
	string longestPalindrome(string s) {
		if (s.empty())
			return "";
		if (s.length() == 1)
			return s;
		int nn = s.find("aueua");
		map<char, vector<int>>charpos;
		for (int i = 0; i < s.length(); i++)
			charpos[s[i]].push_back(i);
		map<int,char>aa;
		for (map<char, vector<int>>::iterator it = charpos.begin(); it != charpos.end(); it++)
			if (it->second.size() == 1)
				aa[it->second[0]]=(it->first);
		vector<char>single;
		for (map<int, char>::iterator it = aa.begin(); it != aa.end(); it++)
			single.push_back(it->second);
		vector<string>strs; vector<map<char, vector<int>>>veccharpos;
		if (single.size()>1)
		{
			strs.push_back(string(s.begin(), s.begin() + charpos[single[1]][0]));
			strs.push_back(string(s.begin() + charpos[single[single.size() - 2]][0] + 1, s.end()));
			for (int i = 1; i < single.size() - 1; i++)
				strs.push_back(string(s.begin() + charpos[single[i - 1]][0] + 1, s.begin() + charpos[single[i + 1]][0]));
			for (int i = 0; i < strs.size(); i++)
			{
				string ss = strs[i];
				map<char, vector<int>>tempcharpos;
				for (int j = 0; j < ss.length(); j++)
					tempcharpos[ss[j]].push_back(j);
				veccharpos.push_back(tempcharpos);
			}
		}
		else
		{
			strs.push_back(s);
			veccharpos.push_back(charpos);
		}
		int maxlen = 1; string ret; ret += s[0];
		for (int h = 0; h < strs.size(); h++)
		{
			string ss = strs[h];
			map<char, vector<int>>sscharpos = veccharpos[h];
			for (map<char, vector<int>>::iterator it = sscharpos.begin(); it != sscharpos.end(); it++)
			{
				if (it->second.size() > 1)
				{
					int kk = it->second.size() - 1;
					bool f = true;
					while (kk >= 1 && f)
					{
						f = false;
						for (int i = 0; i + kk <= it->second.size() - 1; i++)
						{
							if (it->second[i + kk] - it->second[i] + 1 > ret.length())
							{
								f = true;
								if (is_palindrome(ss, it->second[i], it->second[i + kk]))
								{
									ret = string(ss.begin() + it->second[i], ss.begin() + it->second[i + kk] + 1);
								}
							}
						}
						kk--;
					}
				}
			}
		}
		return ret;
	}
};


accepted



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值