Sort Strings by Length
PHP
Medium
4 views
Problem Description
Sort n strings by length, and for equal length sort lexicographically.
Input Format
First n. Next n lines strings.
Output Format
n lines sorted.
Sample Test Case
Input:
4
pear
apple
kiwi
fig
Output:
fig
kiwi
pear
apple
Official Solution
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$n=intval(trim($inputLines[0] ?? '0'));
$arr=[];
for($i=1;$i<=$n;$i++) $arr[] = $inputLines[$i] ?? '';
usort($arr,function($a,$b){
$la=strlen($a); $lb=strlen($b);
if($la===$lb) return $a <=> $b;
return $la <=> $lb;
});
echo implode(PHP_EOL,$arr);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!