![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 <bits/stdc++.h> 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 << solve(S) << endl; }
Input
"fega))))))"
Output
1
Advertisements