Showing posts with label Super Reduced String Hacker Rank Solution. Show all posts
Showing posts with label Super Reduced String Hacker Rank Solution. Show all posts

Tuesday, 31 October 2017

Super Reduced String Hacker Rank Solution in C/C++


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

Solution in C:

#include <math.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    
   {
       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;
}