【LeetCode】 5. Longest Palindromic Substring 最长回文子串(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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"
题目大意
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
解题方法
从中心向外扩散:分为两种情况,1、为奇数,以自己为中心,左右两边扩散;2、为偶数,以自己和右边为中心,左右两边扩散。
class Solution {
public String longestPalindrome(String s) {
String res = "";
if (s == null || s.equals("")) return res;
for (int i = 0; i < s.length(); i++) {
for (int j = 0; (i - j) >= 0 && (i + j + 1) < s.length(); j++) {
if (s.charAt(i - j) != s.charAt(i + j + 1)) break;
if ((2 * j + 2) > res.length()) res = s.substring(i - j, i + j + 2);
}
for (int j = 0; (i - j) >= 0 && (i + j) < s.length(); j++) {
if (s.charAt(i - j) != s.charAt(i + j)) break;
if ((2 * j + 1) > res.length()) res = s.substring(i - j, i + j + 1);
}
}
return res;
}
}
执行用时 :47 ms, 在所有 Java 提交中击败了53.62%的用户
内存消耗 :41.1 MB, 在所有 Java 提交中击败了12.08%的用户