美文网首页leetcode-algorithm
leetcode-005 Longest Palindromic

leetcode-005 Longest Palindromic

作者: hylexus | 来源:发表于2016-09-16 17:56 被阅读62次

    [TOC]

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

    思路分析

    最长回文最简单最直观的思路就是:

    • 从某个中点(middle)向两边扫描之道不是回文
      • 中点紧邻的两个点记为left和right
      • left 和 right有可能相等(字符串长度为偶数时)
      • 直到不是回文的时候将该轮循环的子串和上轮做比较取较长者
    • 遍历所有的可能性---O(n^2)

    代码

    java

    public class Solution005 {
        private String longestPalindrome(String s, int left, int right) {
            while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }
            return s.substring(left + 1, right);
        }
    
        public String longestPalindrome(String s) {
            if (s == null || s.length() == 0)
                return "";
            String ret = "";
            for (int i = 0; i < s.length() * 2 - 1; i++) {
                int left = i / 2;
                int right = i / 2;
                if ((i & 1) == 1)// 奇数
                    right++;
                String tmp = this.longestPalindrome(s, left, right);
                if (ret.length() < tmp.length())
                    ret = tmp;
            }
            return ret;
        }
    
    }
    
    

    python

    class Solution005(object):
        
        def longestStr(self, s, left, right):
            l = len(s)
            while left >= 0 and right < l and s[left] == s[right]:
                left -= 1
                right += 1
            return s[left + 1:right]
                
            
        
        def longestPalindrome(self, s):
            """
            :type s: str
            :rtype: str
            """
            if not s : return ""
            
            ret = "";i = 0
            for i in range(len(s) * 2 - 1):
                left = i / 2
                right = i / 2
                if (i & 1) == 1:right += 1
                
                tmp = self.longestStr(s, left, right)
                
                if len(tmp) > len(ret):ret = tmp
            
            return ret
    
    

    相关文章

      网友评论

        本文标题:leetcode-005 Longest Palindromic

        本文链接:https://www.haomeiwen.com/subject/jjdiettx.html