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

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[n] = '\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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值