From c14d9f3154db24b3903e94fccfb685cec133dc2d Mon Sep 17 00:00:00 2001 From: zeekling Date: Sun, 15 Nov 2020 23:12:52 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9C=80=E9=95=BF=E5=9B=9E=E6=96=87=E5=AD=90?= =?UTF-8?q?=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leetcode/string/LongestPalindrome.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/main/java/com/leetcode/string/LongestPalindrome.java diff --git a/src/main/java/com/leetcode/string/LongestPalindrome.java b/src/main/java/com/leetcode/string/LongestPalindrome.java new file mode 100644 index 0000000..b047df3 --- /dev/null +++ b/src/main/java/com/leetcode/string/LongestPalindrome.java @@ -0,0 +1,61 @@ +package com.leetcode.string; + +/** + * + 最长回文子串: + 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 + +示例 1: + +输入: "babad" +输出: "bab" +注意: "aba" 也是一个有效答案。 +示例 2: + +输入: "cbbd" +输出: "bb" + +来源:力扣(LeetCode) +链接:https://leetcode-cn.com/problems/longest-palindromic-substring +著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + + * @author zeek + * + */ +public class LongestPalindrome { + + + public String longestPalindrome(String s) { + if (s == null || s.length() < 1) { + return ""; + } + int start = 0, end = 0; + for (int i = 0; i < s.length(); i++) { + int len1 = expandAroundCenter(s, i, i); + int len2 = expandAroundCenter(s, i, i + 1); + int len = Math.max(len1, len2); + if (len > end - start) { + start = i - (len - 1) / 2; + end = i + len / 2; + } + } + return s.substring(start, end + 1); + + } + + public int expandAroundCenter(String s, int left, int right) { + while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { + --left; + ++right; + } + return right - left - 1; + } + + + public static void main(String[] args) { + LongestPalindrome rome = new LongestPalindrome(); + String s = "cbbd"; + String res = rome.longestPalindrome(s); + System.out.println(res); + } +}