Last active
June 19, 2020 04:54
-
-
Save debabratakarfa/454d3a3ab9b11622e7db33c9695a3404 to your computer and use it in GitHub Desktop.
Longest Palindromic Substring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Problem: 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. | |
* | |
* Summary: This article is for intermediate readers. It introduces the following ideas: Palindrome, Dynamic Programming and String Manipulation. Make sure you understand what a palindrome means. A palindrome is a string which reads the same in both directions. For example, SS = "aba" is a palindrome, SS = "abc" is not. | |
* | |
* Letcode Submission: https://leetcode.com/submissions/detail/355341568/ | |
*/ | |
/** | |
* Class Solution | |
*/ | |
class Solution { | |
/** | |
* @param String $data Input String. | |
* @return false|string|null $longest_str Longest String. | |
*/ | |
function longestPalindrome($data) { | |
if(empty($data)) | |
{ | |
return ""; | |
} | |
$rev = strrev($data); | |
$len = strlen($data); | |
$longest_len = 0; | |
$longest_str = null; | |
for ($i = 0; $i < $len; ++$i) | |
{ | |
for ($j = $len - $i; $j > $longest_len; --$j) | |
{ | |
if (substr($data, $i, $j) == substr($rev, $len-$i-$j, $j)) | |
{ | |
$longest_len = $j; | |
$longest_str = substr($data, $i, $j); | |
break; | |
} | |
} | |
} | |
return $longest_str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment