标签:
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 { public: string longestPalindrome(string s) { int len = s.length(); int max_l = 0;//最长回文子串长度 int max_s = 0;//最长回文子串开头的位置 int cur_len; int cur_s; for (int i = 0; i < len; i++) {//字符串的长度是奇数 for (int j = 0; i + j<len&&i - j>-1; j++) { if (s[i + j] != s[i - j]) { break; } cur_len = j * 2 + 1; cur_s = i - j; } if (cur_len > max_l) { max_s = cur_s; max_l = cur_len; } for (int j = 0; i - j > -1 && i + j + 1 < len; j++) {//字符串为偶数长度 if (s[i + j + 1] != s[i - j]) { break; } cur_len = 2 * j + 2; cur_s = i - j; } if (cur_len > max_l) { max_s = cur_s; max_l = cur_len; } } return s.substr(max_s, max_l); } };
5. Longest Palindromic Substring
标签:
原文地址:http://www.cnblogs.com/zhoudayang/p/5122975.html