LeetCode 214: Shortest Palindrome Solution
Master LeetCode problem 214 (Shortest Palindrome), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
214. Shortest Palindrome
Problem Explanation
Explanation
To solve this problem, we can follow these steps:
- Find the longest palindrome substring starting from the beginning of the given string
s. - Remove the palindrome substring from the given string and reverse the remaining substring.
- Append the reversed substring to the original string to get the shortest palindrome.
The time complexity of this approach is O(n^2) where n is the length of the input string s. The space complexity is O(n).
Solution Code
class Solution {
public String shortestPalindrome(String s) {
int i = 0;
for (int j = s.length() - 1; j >= 0; j--) {
if (s.charAt(i) == s.charAt(j)) {
i++;
}
}
if (i == s.length()) {
return s;
}
String remaining = s.substring(i);
String remainingReversed = new StringBuilder(remaining).reverse().toString();
return remainingReversed + shortestPalindrome(s.substring(0, i)) + remaining;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 214 (Shortest Palindrome)?
This page provides optimized solutions for LeetCode problem 214 (Shortest Palindrome) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 214 (Shortest Palindrome)?
The time complexity for LeetCode 214 (Shortest Palindrome) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 214 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 214 in Java, C++, or Python.