C++ · problem solving

HackerRank “Super Reduce String”

Shil has a string, , consisting of lowercase English letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string “” would become either “” or “” after operation.

Shil wants to reduce as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Shil out by finding and printing ‘s non-reducible form!

Note: If the final string is empty, print .

Input Format

A single string, .

Constraints

Output Format

If the final string is empty, print ; otherwise, print the final non-reducible string.

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

Solution 

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s;
    getline(cin, s);
    int j;
    for (int i = 0; i < s.length()-1; i++)
    {
       j = i + 1;
       if (s[i] == s[j])
       {
         s.erase(i,2);
         if (s.empty())
         {
          cout << "Empty String" << endl;
          break;
         }
          i = -1; 
       }
    }
 cout << s << endl;
 return 0;
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s