Steve has a string of lowercase characters in range ascii[‘a’..’z’]. He wants to reduce the string to its shortest length by doing a series of operations. In each operation he selects a pair of adjacent lowercase letters that match, andhe deletes them. For instance, the string aab could be shortened to b in one operation.
Steve’s task is to delete as many characters as possible using this method and print the resulting string. If the final string is empty, print "Empty String" without quotes.
characters can be deleted only if they form a pair and are same(i.e from aaa we can only delete 2 a's and will be left with a single a).
Example:
Input: s = "aaabccddd"
Output: abd
Approach
C++
#include <bits/stdc++.h>using namespace std;string superReducedString(string s){while (true){int n = s.size();for (int i = 0; i < n - 1; i++){if (s[i] == s[i + 1]){s.erase(i, 2);i = i + 2;}}if (s.size() == 0)break;else{int i = 0;while (i < s.size() - 1){if (s[i] != s[i + 1])i++;elsebreak;}if (i == s.size() - 1)break;}}if (s.size() == 0)return "Empty String";return s;}int main(){string s = "aaabccddd";string result = superReducedString(s);cout << result << "\n";return 0;}
No comments:
Post a Comment