Problem:
Given a String, find the next bigger lexicographically string.
Input Format:
String
Output Format:
next bigger lexicographically string
next bigger lexicographically string
Constraints:
none
none
Sample Input
zcfedba
Sample Output:
zdabcef
zdabcef
Explanations:-
when compare characters from right to left, c < f, next bigger available character to c is d and rest series is sorted order of remaining characters.
Solution:
@arr=split("",$str);
$len=@arr;
$count=1;
for($j=$len-1;$j>0;$j--)
{
$count++;
$c1=ord($arr[$j]);
$c2=ord($arr[$j-1]);
if($c1>$c2)
{
@r=splice(@arr,$j-1,$count);
@s=sort(@r);
for($m=0;$m<@s;$m++)
{
$c3=ord($s[$m]);
$c4=ord($r[0]);
$c5=ord($s[$m+1]);
if($c3 == $c4 and $c3!=$c5)
{
$arr[$j-1] = $s[$m+1];
@s1=splice(@s,$m+1,1);
push(@arr,@s);
last;
}
}
last;
}
}
$ans=join("",@arr);
print "$ans";
Tips:
Splice is used to remove some elements of array and store them somewhere else.
No comments:
Post a Comment