您的位置:首页 > 其它

关于括号匹配的一些问题总结

2013-08-25 18:06 309 查看
1  九度OJ 1153

使用栈简单的匹配

http://ac.jobdu.com/problem.php?pid=1153

#include <stdio.h>
#include <stack>
#include <string.h>
using namespace std;

int main(){
char str[100];
char out[100];
stack<int> s;
while(scanf("%s",str) != EOF){
int n = strlen(str);
memset(out,' ',sizeof(out));
for(int i=0; i<n; i++){
if(str[i] == '('){
s.push(i);
}else if(str[i] == ')'){
if(s.size() > 0)
s.pop();
else
out[i] = '?';
}
}
while(s.size() > 0){
int k = s.top();
s.pop();
out[k] = '$';
}
out
= '\0';
printf("%s\n%s\n",str,out);
}
return 0;
}

2. 九度 1337
找最长的合法字串

 使用数组模拟栈

#include <stdio.h>
char s[1000001];
int opt[1000001];
int stack[1000000], m, ans, l, cnt, i, last, ll;
int main() {
int n;
while (scanf("%d %s", &n, s) != EOF) {
opt[0] = opt[1] = 0;
cnt = l = ans = m = last =0;
for (i = 1; i <= n; i++) {
if (s[i-1] == '(') {
stack[l++] = i;
opt[i] = 0;
} else {
if(l){
l--;
opt[i] = opt[stack[l]-1] + 2;
if(s[i-2] == ')')
opt[i] += opt[i-1];
opt[stack[l] - 1] = opt[i];
}else
opt[i] = 0;
}
if(opt[i] > ans){
ans = opt[i];
cnt = 1;
}else if(opt[i] == ans) cnt ++;
}
if(ans)
printf("%d %d\n", ans, cnt);
else
printf("0 1\n");

}
return 0;
}

3. 九度 1342
#include <stdio.h>
char s[1000001];
int i, l, r, ans;
int main(){
while (scanf("%s",s) != EOF) {
l = ans = 0;
for(i=0; s[i]; i++){
if(s[i] == '('){
l++;
}else{
if(l){
ans += 2;
l--;
}
}
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: