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