A bracket sequence is a string that contains only characters '(' and ')'.
A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences '()()' and '(())' are correct. The resulting expressions of these sequences are: '(1)+(1)' and '((1+1)+1)'. However, '(', ')(', and '(' are incorrect bracket sequences.
You are given a bracket sequence , where denotes the type of 's a bracket (open or close). It is not mandatory that is necessarily correct. Your task is to determine the number of 's such that is a correct bracket sequence.
Example:
Input: s = ")()()("
Output: 3
Approach
C++
#include <bits/stdc++.h>using namespace std;int bracketSequences(string s){int n = s.size();int cnt = 0;int l = 0;for (int i = 0; i < n; i++){if (s[i] == '(')l++;}int r = n - l;if (l != r)return 0;else{l = 0;int x = 0, y = 0;for (int i = 0; i < n; i++){if (s[i] == '(')l++;elsel--;if (l < y){y = l;x = i + 1;}}reverse(s.begin(), s.begin() + x);reverse(s.begin() + x, s.end());reverse(s.begin(), s.end());l = 0;for (int i = 0; i < n; i++){if (s[i] == '(')l++;elsel--;if (l == 0)cnt++;}return cnt;}}int main(){string s = ")()()(";cout << bracketSequences(s) << "\n";return 0;}
No comments:
Post a Comment