Write a c program a string consisting of lowercase English alphabetic letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation. To do this, he will repeat the above operation as many times as it can be performed and to find & print’s non-reducible form. Note: If the final string is empty, print Empty String.
Input: aaabccddd
Output: abd
Input: baab
Output: Empty String
Input: aaabccddd
Output: abd
Input: baab
Output: Empty String
Solution in C:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main()
{
char* s = (char *)malloc(512000 * sizeof(char));
scanf("%s", s);
int l,i=0,flag;
l=strlen(s);
do
char* s = (char *)malloc(512000 * sizeof(char));
scanf("%s", s);
int l,i=0,flag;
l=strlen(s);
do
{
flag=0;
for(i=0;i<l-1;)
{
if(s[i]==s[i+1])
{
flag=0;
for(i=0;i<l-1;)
{
if(s[i]==s[i+1])
{
flag=1;
for(int j=i;j<l-2;j++)
s[j]=s[j+2];
l=l-2;
}
else
i++;
}
s[l]='\0';
} while(flag==1&&l>0);
if(l!=0)
printf("%s",s);
else
printf("Empty String");
return 0;
}
Solution in C++
#include <iostream>
#include <string>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
string s;
cin>>s;
for(int i=1;i<s.length();i++)
{
if(s[i] == s[i-1])
{
s.erase(i-1,2);
i=0;
}
}
if(s.length() == 0)
cout<<"Empty String";
else
cout<<s;
return 0;
}
In the above program, what does erase(i-1,2); do? explain about the arguments passed please.
ReplyDeleteerase(i-1,2) - removes the two elements starting from index (i-1)
Deletewhy is i again declared as 0
ReplyDeleteBecause whenever we delete few characters of the string, the size of the string is changing, and also the indexes assigned for each remaining characters change. So after every deletion it is important to point our index to the beginning of the string.
ReplyDeletehow this code work if string is not sorted
ReplyDeletecan someone explain why i is declared as 0 inside the loop??
ReplyDeleteBecause whenever we delete few characters of the string, the size of the string is changing, and also the indexes assigned for each remaining characters change. So after every deletion it is important to point our index to the beginning of the string.
DeleteFor traversing the string again from 0th index
ReplyDelete