Longest Common Prefix
PHP
Hard
3 views
Problem Description
Given n strings, print their longest common prefix (or empty).
Input Format
First n. Next n lines strings.
Output Format
One line prefix.
Sample Test Case
Input:
3
flower
flow
flight
Official Solution
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$n=intval(trim($inputLines[0] ?? '0'));
if($n<=0){ echo ''; exit; }
$pref=$inputLines[1] ?? '';
for($i=2;$i<=$n;$i++){
$s=$inputLines[$i] ?? '';
$j=0;
$lim=min(strlen($pref),strlen($s));
while($j<$lim && $pref[$j]===$s[$j]) $j++;
$pref=substr($pref,0,$j);
if($pref==='') break;
}
echo $pref;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!