aiheshan

有多自律,才能有多自由

导航

leetcode 5. Longest Palindromic Substring

https://leetcode.com/problems/longest-palindromic-substring/

 题目:求字符串最长回文串。

 第一种思路:以每一个字符为回文串中间的字符时,最长的回文串。考虑回文串字符个数为奇数,偶数的2种情况。

x--,j++ 的向两边扩展,判断最长的回文串。

 1 class Solution {
 2 public:
 3     string longestPalindrome(string s) {
 4         int max_value =0;
 5         int i;
 6         string result;
 7         int k=s.length();
 8         for(i=0;i<k;i++){
 9           int x,y,temp=1;
10           int j;
11           for(j=i-1;j<i+1;j++){
12             x=j;
13             y=i+1;
14             temp=i-j;
15             while(x>=0&&y<k&&s[x]==s[y]){
16                 temp+=2;
17                 x--;y++;
18             }
19             if(temp>max_value){
20               max_value = temp;
21               result=s.substr(x+1,y-x-1);
22             }
23           }
24         }
25         return result;
26         
27     }
28 };

在leetcode上运行时长为60s.

posted on 2016-08-13 20:41  aiheshan  阅读(186)  评论(0编辑  收藏  举报