g0001_0100.s0005_longest_palindromic_substring.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0005_longest_palindromic_substring;
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Dynamic_Programming
// #Data_Structure_II_Day_9_String #Algorithm_II_Day_14_Dynamic_Programming
// #Dynamic_Programming_I_Day_17 #Udemy_Strings #Big_O_Time_O(n)_Space_O(n)
// #2023_08_09_Time_7_ms_(97.94%)_Space_41.9_MB_(56.27%)
/**
* 5 - Longest Palindromic Substring\.
*
* Medium
*
* Given a string `s`, return _the longest palindromic substring_ in `s`.
*
* **Example 1:**
*
* **Input:** s = "babad"
*
* **Output:** "bab" **Note:** "aba" is also a valid answer.
*
* **Example 2:**
*
* **Input:** s = "cbbd"
*
* **Output:** "bb"
*
* **Example 3:**
*
* **Input:** s = "a"
*
* **Output:** "a"
*
* **Example 4:**
*
* **Input:** s = "ac"
*
* **Output:** "a"
*
* **Constraints:**
*
* * `1 <= s.length <= 1000`
* * `s` consist of only digits and English letters.
**/
public class Solution {
public String longestPalindrome(String s) {
char[] newStr = new char[s.length() * 2 + 1];
newStr[0] = '#';
for (int i = 0; i < s.length(); i++) {
newStr[2 * i + 1] = s.charAt(i);
newStr[2 * i + 2] = '#';
}
int[] dp = new int[newStr.length];
int friendCenter = 0;
int friendRadius = 0;
int lpsCenter = 0;
int lpsRadius = 0;
for (int i = 0; i < newStr.length; i++) {
dp[i] =
friendCenter + friendRadius > i
? Math.min(dp[friendCenter * 2 - i], (friendCenter + friendRadius) - i)
: 1;
while (i + dp[i] < newStr.length
&& i - dp[i] >= 0
&& newStr[i + dp[i]] == newStr[i - dp[i]]) {
dp[i]++;
}
if (friendCenter + friendRadius < i + dp[i]) {
friendCenter = i;
friendRadius = dp[i];
}
if (lpsRadius < dp[i]) {
lpsCenter = i;
lpsRadius = dp[i];
}
}
return s.substring((lpsCenter - lpsRadius + 1) / 2, (lpsCenter + lpsRadius - 1) / 2);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy