思路:挨着累计'('的个数,遇到')'就完成一次匹配, 把情况数乘进答案。
java代码:
import java.util.*;
public class Main {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
String str = in.nextLine();
Stack<Character> stack = new Stack<Character>();
int num =0,res=1;
for(int i =str.length()-1;i>=0;i--){
if(str.charAt(i)=='('){
char c =stack.pop();
if(c!=')'){
System.out.print(0);
return;
}
res = res*num;
num--;
}else{
stack.push(str.charAt(i));
num++;
}
}
System.out.print(res);
}
}
c++ 代码:
#include <bits/stdc++.h>
using namespace std;
string s;
int main() {
cin >> s;
int ans = 1, cnt = 0;
for(int i = 0; i < s.size(); i++) {
if(s[i] == '(') {
cnt++;
} else {
ans *= cnt;
cnt--;
}
}
cout << ans << endl;
}