214. Shortest Palindrome #577
-
Topics: You are given a string Return the shortest palindrome you can find by performing this transformation. Example 1:
Example 2:
Constraints:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the shortest palindrome by adding characters in front of a given string. We can approach this by identifying the longest prefix of the string that is already a palindrome. Once we have that, the remaining part can be reversed and added to the front to make the entire string a palindrome. Approach:
To do this efficiently, we can use string matching techniques such as the KMP (Knuth-Morris-Pratt) algorithm to find the longest palindromic prefix. Step-by-Step Solution:
Let's implement this solution in PHP: 214. Shortest Palindrome <?php
/**
* @param String $s
* @return String
*/
function shortestPalindrome($s) {
// If the string is empty, return an empty string
if (empty($s)) {
return $s;
}
// Reverse of the string
$rev_s = strrev($s);
// Form the new string as s + '#' + reverse(s)
$combined = $s . '#' . $rev_s;
// Compute the LPS array for this combined string
$lps = computeLPS($combined);
// Length of the longest palindromic prefix in s
$longest_palindromic_prefix_len = $lps[strlen($combined) - 1];
// The characters that need to be added to the front are the remaining part of the string
$remaining = substr($s, $longest_palindromic_prefix_len);
// Add the reverse of the remaining part to the front of s
return strrev($remaining) . $s;
}
/**
* Helper function to compute the KMP (LPS array) for string matching
*
* @param $pattern
* @return array
*/
function computeLPS($pattern) {
$n = strlen($pattern);
$lps = array_fill(0, $n, 0);
$len = 0;
$i = 1;
while ($i < $n) {
if ($pattern[$i] == $pattern[$len]) {
$len++;
$lps[$i] = $len;
$i++;
} else {
if ($len != 0) {
$len = $lps[$len - 1];
} else {
$lps[$i] = 0;
$i++;
}
}
}
return $lps;
}
?> Explanation:
Time Complexity:
Example Walkthrough:Example 1:Input:
Since the whole string is already a palindrome, no characters need to be added. So the output is Example 2:Input:
So, we add Conclusion:This solution efficiently finds the shortest palindrome by leveraging string matching techniques and the KMP algorithm to identify the longest palindromic prefix. The complexity is linear, making it suitable for large input sizes up to |
Beta Was this translation helpful? Give feedback.
We need to find the shortest palindrome by adding characters in front of a given string. We can approach this by identifying the longest prefix of the string that is already a palindrome. Once we have that, the remaining part can be reversed and added to the front to make the entire string a palindrome.
Approach:
s
that is already a palindrome.To do this eff…