zoukankan      html  css  js  c++  java
  • [LC] 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.

    Example 1:

    Input: "babad"
    Output: "bab"
    Note: "aba" is also a valid answer.
    

    Example 2:

    Input: "cbbd"
    Output: "bb"

    Solution 1:
    Time: O(N^2)
    class Solution:
        def longestPalindrome(self, s: str) -> str:
            if len(s) <= 1:
                return s
            self.res = ''
            for i, char in enumerate(s):
                self.helper(i, i, s) # odd
                self.helper(i, i + 1, s) # even
            return self.res
        
        def helper(self, start, end, s, even=False):  
            while start >= 0 and end < len(s):
                if s[start] == s[end]:
                    if end - start >= len(self.res):
                        self.res = s[start: end + 1]
                    start -= 1
                    end += 1
                else:
                    return
            
            
    class Solution {
        int start = 0;
        int maxLen = 0;
        public String longestPalindrome(String s) {
            int len = s.length();
            for (int i = 0; i < len; i++) {
                helper(i, i, s);
                helper(i, i + 1, s);
            }
            return s.substring(start, start + maxLen);
        }
        
        private void helper(int low, int high, String s) {
            while (low >= 0 && high < s.length() && s.charAt(low) == s.charAt(high)) {
                low -= 1;
                high += 1;
            }
            if (high - low - 1 > maxLen) {
                maxLen = high - low - 1;
                start = low + 1;
            }
        }
    }

    Solution 2:

    Time: O(N^2)

    class Solution {
        public String longestPalindrome(String s) {
            if (s == null || s.length() <= 1) {
                return s;
            }
            boolean[][] isPalin = new boolean[s.length()][s.length()];
            int max = 0;
            String res = "";
            for (int i = 1; i < s.length(); i++) {
                // i == j for case of single char
                for (int j = 0; j <= i; j++) {
                    if (s.charAt(i) == s.charAt(j) && (i - j <= 2 || isPalin[i - 1][j + 1])) {
                        isPalin[i][j] = true;
                        if (i - j + 1> max) {
                            max = i - j + 1;
                            // j is smaller than i
                            res = s.substring(j, i + 1);
                        }
                    }
                }
            }
            return res;
        }
    }
  • 相关阅读:
    单例模式
    Java多线程小例子(三个窗口卖火车票)
    HashMap和HashTable的区别
    javascript操作对象的方法
    javascript基本语法
    其他标签
    头标签
    label标签
    表单标签
    IO流-LineNumberReader
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11706959.html
Copyright © 2011-2022 走看看