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, 判斷每一位爲中間位的最大回文子串。 比較便可。指針
public static String longestPalindrome(String s) { //指針p 記錄遍歷位置 int p = 0; //最大長度 int maxLen = 0; //最大子串 String sr = ""; char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i=p+1) { p = i; int tempLenth = 0; String tempS = null; //結尾衛判斷 if (p + 1 == s.length()) { if (sr.length() >= 2) return sr; //已是最後一位 return String.valueOf(chars[p]); } //非迴文,指針日後走 if (p + 2 < s.length() && chars[p + 1] != chars[p] && chars[p + 2] != chars[p]) { p++; } if (p +2 < s.length() && chars[p + 2] == chars[p]) { //奇迴文 int j = 1; while (p - j >= 0 && p + j + 2 <= s.length() - 1 && chars[p - j] == chars[p + 2 + j]) { j++; } tempLenth = 2 * j + 1; tempS = s.substring(p - j + 1, p + j + 2); if (tempLenth > maxLen) { maxLen = tempLenth; sr = tempS; } } if (chars[p + 1] == chars[p]) { //偶迴文 int j = 1; while (p - j >= 0 && p + j + 1 <= s.length() - 1 && chars[p - j] == chars[p + j + 1]) { j++; } tempLenth = 2 * j; tempS = s.substring(p - j + 1, p + j + 1); if (tempLenth > maxLen) { maxLen = tempLenth; sr = tempS; } } } return sr; }
時間複雜度:O(n^2)
空間複雜度:O(n)
耗時:code