【无标题】

/*
给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。

示例 1:

输入:s = "(()"
输出:2
解释:最长有效括号子串是 "()"
示例 2:

输入:s = ")()())"
输出:4
解释:最长有效括号子串是 "()()"
示例 3:

输入:s = ""
输出:0
 

提示:

0 <= s.length <= 3 * 104
s[i] 为 '(' 或 ')'

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct stack_info {
    char ch;
    int index;
};

int longestValidParentheses(char * s)
{
    int len = strlen(s);
    struct stack_info *stack = (struct stack_info *)malloc(len * sizeof(struct stack_info));
    unsigned char *mark = (unsigned char *)malloc(len);
    int i = 0, j = 0, count = 0, max = 0;

    memset(stack, 0, len * sizeof(struct stack_info));
    memset(mark, 0, len);

    stack[0].ch = s[0];

    for (i = 1; i < len; i++) {
        if ((s[i] == ')') && (stack[j].ch == '(')) {
            mark[i] = 1;
            mark[stack[j].index] = 1;
            j--;
            if (j < 0) {
                stack[++j].ch = s[++i];
                stack[j].index = i;
            }
        } else {
            stack[++j].ch = s[i];
            stack[j].index = i;
        }
    }


    //to calc mark value for continued 1
    for (i = 0; i < len; i++) {
        if (mark[i] == 1) {
            max++;
        } else {
            if (max > count) {
                count = max;
            }

            max = 0;
        }
    }

    if (max > count) {
        count = max;
    }

    free(mark);
    free(stack);

    return count;
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        printf("To find longest Valid Parentheses, please input a string!\n");
        return 0;
    }

    printf("%d\n", longestValidParentheses(argv[1]));

    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值