User has n string in english lowercase. In one operation, he can delete any pair of adjacent letters with same value. User wants to reduce string as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help user to find and print most reducible form of string. If the final string is empty, print Empty String.
e.g. aabccaabcc can be reduced to Empty String. aabcaabcc can be reduced to bcb Input Format And Output Format:
Sample Input 0
aaabccddd
Sample Output 0
abd
Sample Input 1
baab
Sample Output 1
Empty String
Sample Input 2
aa
Sample Output 2
Empty String
Explanation
Sample Case 0:
User can perform the following sequence of operations to get the final string:
aaabccddd->abccddd
abccddd->abddd
abddd->abd
Thus, we print abd.
Sample Case 1:
Shil can perform the following sequence of operations to get the final string:
baab->bb
bb->Empty String
Solution:
<?php
$data="aaabccddd"; //Input string
$str=str_split($data);
$len=count($str);
$initial="";
for($i=0;$i<$len;$i++) {
if($initial!="" && $str[$i]==$initial) {
$start=$i-1;
$end=$i+1;
$data1=substr($data,0,$start);
$data2=substr($data,$end);
$data=$data1.$data2;
$str=str_split($data);
$i=0;
$len=$len-2;
$initial="";
}
$initial=$str[$i];
}
if($data) {
echo $data;
}
else {
echo 'Empty String';
}
?>
e.g. aabccaabcc can be reduced to Empty String. aabcaabcc can be reduced to bcb Input Format And Output Format:
Sample Input 0
aaabccddd
Sample Output 0
abd
Sample Input 1
baab
Sample Output 1
Empty String
Sample Input 2
aa
Sample Output 2
Empty String
Explanation
Sample Case 0:
User can perform the following sequence of operations to get the final string:
aaabccddd->abccddd
abccddd->abddd
abddd->abd
Thus, we print abd.
Sample Case 1:
Shil can perform the following sequence of operations to get the final string:
baab->bb
bb->Empty String
Solution:
<?php
$data="aaabccddd"; //Input string
$str=str_split($data);
$len=count($str);
$initial="";
for($i=0;$i<$len;$i++) {
if($initial!="" && $str[$i]==$initial) {
$start=$i-1;
$end=$i+1;
$data1=substr($data,0,$start);
$data2=substr($data,$end);
$data=$data1.$data2;
$str=str_split($data);
$i=0;
$len=$len-2;
$initial="";
}
$initial=$str[$i];
}
if($data) {
echo $data;
}
else {
echo 'Empty String';
}
?>
No comments:
Post a Comment