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.

转载于:https://www.cnblogs.com/aiheshan/p/5759759.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值