版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40984919/article/details/81380813
题意:给你一个字符串,有多少对符合规则的左右括号-----》比如() (()) ((?) (?)) 这里的?可以换为左括号或者右括号
在这个题中,我们可以去找左括号和?的个数,先暂时把?看为右括号。这样,我们在找的时候,就可以很好的去匹配了。
作者的解释基本都在代码里注释了。这就不做过多解释了。
代码:
#include<set>
#include<map>
#include<stack>
#include<bitset>
#include<math.h>
#include<string>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define close ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N=1000000+50;
const int INF=0x3f3f3f3f;
const double EPS = 1e-10;
ll mod = 1e9+7;
string s;
int len,ans;
int main(){
cin>>s;
ans = 0;
len = s.length();
for(int i = 0; i < len; i++){
int lt = 0, rt = 0; //rt代表将?看为);
for(int j = i; j < len; j++){
if(s[j] == '(') lt++;
else if(s[j] == '?'){
if(lt == rt) lt++;
else rt++;
}
else{
if(lt == rt) rt--; //如果此时多出了一个右括号,那么让?为左括号
else lt--;
if(lt < 0) break;
if(rt < 0) break;
}
if((j - i + 1) % 2 == 0 && rt == lt){
ans++;
}
}
}
cout<<ans<<endl;
return 0;
}
/*
********
************
####....#.
#..###.....##....
###.......###### ### ###
........... #...# #...#
##*####### #.#.# #.#.#
####*******###### #.#.# #.#.#
...#***.****.*###.... #...# #...#
....**********##..... ### ###
....**** *****....
#### ####
###### ######
##############################################################
#...#......#.##...#......#.##...#......#.##------------------#
###########################################------------------#
#..#....#....##..#....#....##..#....#....#####################
########################################## #----------#
#.....#......##.....#......##.....#......# #----------#
########################################## #----------#
#.#..#....#..##.#..#....#..##.#..#....#..# #----------#
########################################## ############
*/