C++ program to check whether given string is bad or not

Suppose we have a string S with n characters. S contains lowercase English letters and ')' characters. The string is bad, if the number of characters ')' at the end is strictly greater than the number of remaining characters. We have to check whether S is bad or not.

So, if the input is like S = "fega))))))", then the output will be True, because this is bad as there are 4 letters and 6 ')'s.

Steps

To solve this, we will follow these steps −

ans := 0
n := size of S
i := n - 1
while (i >= 0 and S[i] is same as ')'), do:
   (decrease i by 1)
z := n - 1 - i
ans := 2 * z - n
if ans > 0, then:
   return true
Otherwise
   return false

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;

bool solve(string S) {
   int ans = 0;
   int n = S.size();
   int i = n - 1;
   while (i >= 0 && S[i] == ')')
      i--;
   int z = n - 1 - i;
   ans = 2 * z - n;
   if (ans > 0)
      return true;
   else
      return false;
}
int main() {
   string S = "fega))))))";
   cout 

Input

"fega))))))"

Output

1
Updated on: 2022-03-03T09:57:18+05:30

380 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements