今天在庞果网看到”最长有效括号的长度“这个问题,自己做了一下,自己测试的时候可以通过。但是在提交却说代码测试用例不成功。自己想不出让代码可以失败的例子。有点想不通。但是我还是相信我这个代码还是,如果谁有个可以测试的例子让以下代码不通过的话,在评论说一下。
问题:给定只包含括号字符'('和 ')''的字符串,请找出最长的有效括号内子括号的长度。 举几个例子如下: 例如对于"( ()",最长的有效的括号中的子字符串是"()" ,有效双括号数1个,故它的长度为 2。 再比如对于字符串") () () )",其中最长的有效的括号中的子字符串是"() ()",有效双括号数2个,故它的长度为4。 再比如对于"( () () )",它的长度为6。 换言之,便是有效双括号"()"数的两倍。
#include <stdio.h>
#include <string.h>
int longestValidParentheses(const char *s)
{
int i = 0;
int count = 0;
int left = 0; //左括号
//略过右括号
start:
while (s[i] == ')')
i++;
//())))))
//left = 1;
for (; s[i]; i++)
{
if (s[i] == '(')
left++;
else if (s[i] == ')' && left > 0)
{
count++;
left--;
}
else if (s[i] == ')' && left == 0)
goto start;
}
return count * 2; //长度为括号对的两倍
}
//start 提示:自动阅卷起始唯一标识,请勿删除或增加。
int main()
{
char str[] = "(((())())";
printf("%d\n", longestValidParentheses(str));
return 0;
} #include <stdio.h>
#include <string.h>
int longestValidParentheses(const char *s)
{
int i = 0;
int count = 0;
int left = 0; //左括号
//略过最前面的右括号
start:
while (s[i] == ')')
i++;
//())))))
//left = 1;
for (; s[i]; i++)
{
if (s[i] == '(')
left++;
else if (s[i] == ')' && left > 0)
{
count++;
left--;
}
else if (s[i] == ')' && left == 0)
goto start;
}
return count * 2; //长度为括号对的两倍
}
//start 提示:自动阅卷起始唯一标识,请勿删除或增加。
int main()
{
char str[] = "(((())())";
printf("%d\n", longestValidParentheses(str));
return 0;
}
更新:2013年12月7日 23:11:01
今天问了一下大神,原来是我理解错了。有效长度是指连续的,不允许从中间断开。更改了一下,本来写了一下思路,奈何firefox在快要写好的时候却崩溃,不想再写了。把更改代码发布一下。如果有什么错误,请指出来。
#include <stdio.h>
#include <string.h>
int longestValidParentheses(const char *s)
{
int i = 0;
int count = 0;
int left = 0; //左括号数目
int preCount = 0; //已有最长括号对数目
//略过最前面的右括号
start:
while (s[i] == ')')
i++;
//())()
for (; s[i]; i++)
{
if (s[i] == '(')
left++;
else if (s[i] == ')' && left > 0)
{
count++;
left--;
}
/* 当遇到这种状态,说明前面的有效括号已经结束 */
else if (s[i] == ')' && left == 0)
{
if (count > preCount)
preCount = count;
count = 0; //前面括号已经匹配完,重新计数
goto start;
}
}
return (preCount > count ? preCount : count) * 2; //长度为括号对的两倍
}
int main()
{
char str[] = "(()()))()";
printf("%d\n", longestValidParentheses(str));
return 0;
}