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.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"

先纪念一波……
一个样例没过是因为temp在每个循环初始化不一致。
出一下最终解:
class Solution { public: string longestPalindrome(string s) { int length = s.size(); int left,right; int start,end,temp,max; max = 0; temp = 1; if(length < 2) { return s; } for(int i = 0;i < length;i++) { right = i + 1; while(s[i] == s[right]) { temp += 1; if(temp > max) { start = i; end = right; max = temp; } right++; if(right > length - 1) { break; } } left = i - 1; if((left < 0) || (right > length - 1)) { temp = 1; continue; } while(s[left] == s[right]) { temp += 2; if(temp > max) { start = left; end = right; max = temp; } left--; right++; if((left < 0) || (right > length - 1)) { break; } } max = temp > max?temp:max; temp = 1; } if(max == 1) { start = end = 1; } return s.substr(start, max); // char* q = (char*)malloc(sizeof(char) * (max-1)); // char* p; // p = q; // for(int i = start;i < end + 1;i++) // { // *p = s[i]; // p++; // } // *p = 0; // return q; } };
浙公网安备 33010602011771号