LeetCode OJ : 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, and there exists one unique longest palindromic substring.


求字符串中的最长回文字符串;
我的思路比较简单,但是实现起来代码看着好乱。。。从第一个字符开始遍历,直到最后一个字符,对每一个在index位置的字符进行判断;
如果最长回文字符串是奇数,则判断--index和++index是否相等;
如果最长回文字符串是偶数,则判断index和++index是否相等;


class Solution {
public:
    string longestPalindrome(string s) {
        int maxlen = 0, index = 0, length;
        
        if (s.size() < 3){
            return s;
        }

        for (int i = 0; i < s.size()-1; ++i){
            length = findPalindrome(s, i);
            if (maxlen < length){
                maxlen = length;
                index = i;
            }
        }
        
        if (maxlen % 2 == 0)
            index = index - maxlen/2 + 1;
        else
            index = index - maxlen/2;
        string longestSubString(s, index, maxlen);
        return longestSubString;
    }

    int findPalindrome(string &s, int index){
        int l_index = index-1, r_index = index+1;
        int length1 = 1, length2 = 0;
        
        /*针对abvba这种奇数的情况*/
        while((s[l_index--] == s[r_index++]) && (r_index <= s.size())){
            length1 += 2;
        }
        
        /*针对abba这种偶数的情况*/
        l_index = index;
        r_index = index+1;
        while((s[l_index--] == s[r_index++]) && (r_index <= s.size())){
            length2 += 2;
        }
        
        return (length1 > length2) ?  length1 : length2;
    }
};



虽然代码看着恶习,但是运行效率还阔以,Runtime: 72 ms;我再找找其它的方法;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值