九度oj 题目1342:寻找最长合法括号序列II

题目描述:
假如给你一个由’(‘和’)’组成的一个随机的括号序列,当然,这个括号序列肯定不能保证是左右括号匹配的,所以给你的任务便是去掉其中的一些括号,使得剩下的括号序列能够左右括号匹配且长度最长,即最长的合法括号序列。
输入:
测试数据包括多个,每个测试数据只有一行,即一个随机的括号序列,该括号序列的长度保证不超过106
输出:
对于每个测试案例,输出一个整数,表示最后剩下的最长合法括号序列长度。
样例输入:
(())()
(()
样例输出:
6
2

这个题和1337求的是不一样的
代码如下
 1 #include <iostream>
 2 #include <cstring>
 3 #include <stdio.h>
 4 #include <stdlib.h>
 5 using namespace std;
 6  
 7 char str[1000002];
 8 int main(int argc,char* argv[])
 9 {
10     while(scanf("%s",str)!= EOF) {
11  
12         int temp = 0;
13         int len = strlen(str);
14         int ans = 0;
15         for(int i = 0; i < len; i++) {
16             if(str[i] == '(') {
17                 temp++;
18             }
19             else if(str[i] == ')') {
20                 temp--;
21                 if(temp < 0) {
22                     temp = 0;
23                 }
24                 else {
25                     ans += 2;
26                 }
27             }
28         }
29          
30         printf("%d
",ans);
31     }
32     return 0;
33 }

代码其实可以这样精简

 1 #include <stdio.h>
 2 
 3 char str[1000002];
 4 int main(int argc,char* argv[])
 5 {
 6     while(scanf("%s",str)!= EOF) {
 7         int temp = 0;
 8         int ans = 0;
 9         for(int i = 0; str[i]; i++) {
10             if(str[i] == '(') {
11                 temp++;
12             }
13             else if(temp > 0) {
14                 temp--;
15                 ans += 2;
16             }
17         }
18         
19         printf("%d
",ans);
20     }
21     return 0;
22 }
原文地址:https://www.cnblogs.com/jasonJie/p/5777859.html