Problem:
Given a string, you need to convert to a different string such that consecutive characters should be different. Only operation allowed is to delete any alphabet of string. Find minimum number of deletion required
Input Format:
number of test cases T
next T lines contains a string to be tested
next T lines contains a string to be tested
Output Format:
Minimum number of deletion required
Minimum number of deletion required
Constraints:
none
none
Sample Input
3
ababa
aaaabbbb
acbbca
ababa
aaaabbbb
acbbca
Sample Output:
0
6
1
0
6
1
Explanations:
ababa already have proper condition.
aaaabbbb = ab, so 3 a and 3 b deleted, so ans is 3+3=6
acbbca = acbca, so only 1 b need to be deleted
ababa already have proper condition.
aaaabbbb = ab, so 3 a and 3 b deleted, so ans is 3+3=6
acbbca = acbca, so only 1 b need to be deleted
Solution:
for($i=0;$i<$t;$i++)
{
chomp($s=<STDIN>);
@arr=split("",$s);
$len=@arr;
$len--;
$ans=0;
for($j=0;$j<$len;$j++)
{
if($arr[$j] eq $arr[$j+1])
{
$ans++;
}
}
push(@out,$ans);
}
foreach(@out)
{
print "$_\n";
}
Tips:
just increment counter if neighbours are same.
chomp($n=);
ReplyDelete$s=();
$cnt=0;
for($i=0;$i<$n;$i=$i+1){
chomp($s=);
while($s=~/(.)(\1+)/g){
$s= "$`$1$'";
@cnt=split("",$2);
$cnt=$cnt+@cnt;
}
push @arr,$s;
push @a,$cnt;
}
foreach($i=0;$i<$n;$i=$i+1){
print "result is $arr[$i] after delete $a[$i]\n";
}