/*
给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
示例 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;
}
【无标题】
最新推荐文章于 2024-07-19 19:11:19 发布