[Leetcode 5, Easy] Longest Palindromic Substring

本文介绍了如何使用C++、Java和Python解决寻找字符串中最长回文子串的问题,包括两种方法:通过字符对称性生成子串和通过连续相同字符生成子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ProblemGiven 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.

Analysis: The basic idea of this problem is to check whether a sub-string to be palindromic, which is generated by one of the following two methods:

(1) Take a character from the string, and concat two substrings, one of which ends with the left character of the given one and the other starts with the right character of the given one.

(2) Find two consequent same characters. Concat two substrings, one of which ends with the left char, and the other one starts with the right one.

Take the start index and the maximal length of the substrings. The index should not be smaller than 0 and not over the length of the string. 

Solutions

(1) C++:

string longestPalindrome(string s) {
        if(s.size() == 0 || 
           s.size() == 1 || 
           (s.size() == 2 && s[0] == s[1]))
            return s;

        int maxLen = 0;
        int start = 0;
        int size = s.size();
        for(int midIndex = 1; midIndex < size - 1; ++midIndex) {
            for (int i = 1; ; ++i)
                if(i > midIndex || 
                   i >= size - midIndex || 
                   s[midIndex - i] != s[midIndex + i]) {
                    if(maxLen < 2*(i - 1) + 1) {
                        maxLen = 2*(i - 1) + 1;
                        start = midIndex - i + 1;
                    }
                    break;
                }
        }
        
        for(int left = 0, right = 1; right < size; ++left, ++right) {
            for (int i = 0; ; ++i)
                if(i > left || 
                   i >= size - right || 
                   s[left - i] != s[right + i]) {
                    if(maxLen < 2*(i - 1) + 2) {
                        maxLen = 2*(i - 1) + 2;
                        start = left - i + 1;
                    }
                    break;
                }
        }
        
        return s.substr(start, maxLen);
    }


(2) Java:


(3) Python:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值