PHP Program to Longest Palindromic Substring Length with Explanation
PHP
Hard
PHP Strings
32 views
1 min read
80 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around length, longest, palindromic. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Print the length of the longest palindromic substring (expand-around-center).
Input Format
One line string s.
Output Format
One integer length.
Constraints
|s|
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$n=strlen($inputText);
$best=1;
for($c=0;$c<$n;$c++){
$l=$c; $r=$c;
while($l>=0 && $r<$n && $inputText[$l]===$inputText[$r]){ $best=max($best,$r-$l+1); $l--; $r++; }
$l=$c; $r=$c+1;
while($l>=0 && $r<$n && $inputText[$l]===$inputText[$r]){ $best=max($best,$r-$l+1); $l--; $r++; }
}
echo $best;
?>
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Print the length of the longest palindromic substring (expand-around-center).
Input / Output
Output
One integer length.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$n=strlen($inputText);
$best=1;
for($c=0;$c<$n;$c++){
$l=$c; $r=$c;
while($l>=0 && $r<$n && $inputText[$l]===$inputText[$r]){ $best=max($best,$r-$l+1); $l--; $r++; }
$l=$c; $r=$c+1;
while($l>=0 && $r<$n && $inputText[$l]===$inputText[$r]){ $best=max($best,$r-$l+1); $l--; $r++; }
}
echo $best;
?>
Solutions (0)
No solutions submitted yet. Be the first!