LeetCode第5题 最长回文子串longestPalindrome(附java和python代码)

给你一个字符串 s,找到 s 中最长的回文子串。题目链接

示例 1:

输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。

示例 2:

输入:s = "cbbd"
输出:"bb"

实现:

1、 分两个for循环来执行

2、第一个for循环是以每一个字符串为中心轴外扩,形如"a","aba","abcba"这样的子串的中心对称。

3、第二个for循环是以虚拟轴线为中心轴外扩,形如"aa","abba"这样的虚拟轴线对称。

4、cnt为一半的最长子串长度,该字符串只增不减少,在循环过程只只考虑长度大于最长子串的可能性,进行剪枝

class Solution {
    public String longestPalindrome(String s) {
        if(isHui(s)){
            return s;
        }
        String temp = "";
        int res = 0;
        int cnt=0;
        for(int i = 0; i=0)&&(i+cntres){
                    temp = s.substring(i-cnt, i+cnt+1);
                    res = Math.max(res, 2*cnt+1);
                }
                cnt ++;
            }
        }
        cnt=1;
        for(int i = 0; i=0)&&(i+cnt-1res){
                    temp = s.substring(i-cnt, i+cnt);
                    res = Math.max(res, 2*cnt);
                }
                cnt ++;
            }
        }
        return temp;
    }

    public boolean isHui(String s){
        Stack stack = new Stack<>();
        for(Character c:s.toCharArray()){
            stack.add(c);
        }
        for(Character c:s.toCharArray()){
            if(c!=stack.pop()){
                return false;
            }
        }
        return true;
    }
}

Python代码

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if(self.isHui(s)):
            return s 
        temp = ""
        res = 0
        cnt = 0
        for i in range(len(s)):
            while (i - cnt >=0) and (i + cnt < len(s)) and self.isHui(s[i-cnt:i+cnt+1]):
                if(2 * cnt + 1 > res):
                    temp = s[i-cnt:i+cnt+1]
                    res = max(res, 2 * cnt + 1)
                    cnt += 1
        cnt = 1
        for i in range(len(s)):
            while (i - cnt >= 0) and (i + cnt -1 < len(s)) and self.isHui(s[i-cnt:i+cnt]):
                if(2 * cnt > res):
                    temp = s[i-cnt:i+cnt]
                    res = max(res, 2 * cnt)
                cnt += 1 
        return temp

    def isHui(self, s):
        stack = []
        for c in s:
            stack.append(c)
        for c in s:
            if c != stack.pop():
                return False
        return True

你可能感兴趣的:(学习笔记,随便写点,leetcode,算法,职场和发展)