平衡括号(堆栈实现)

时间:2017-10-09 18:24:21

标签: c

我为平衡括号问题编写了这段代码,但我似乎不知道为什么它会在某些测试用例中给出分段错误逻辑上代码是正确的,因为它传递了50%的测试用例。 https://www.hackerrank.com/challenges/balanced-brackets/problem

char* isBalanced(char* s)
{
    // Complete this function
    char* stack = (char *)malloc(5000 * sizeof(char));
    int t=-1,i;
    for(i=0; s[i] !='\0'; i++)
    {
        if(t==-1)
        {
            stack[++t]=s[i];
        }
        else
        {
            if(stack[t]==s[i]-2 || stack[t]==s[i]-1) //the statement is correct (uses ascii code concept)
            {
                t--;
            }
            else
            {
                stack[++t]=s[i];
            }
        }
    }
    char *yes="YES";
    char *no="NO";
    if(t==-1)
        return yes;
    else
        return no;
}

int main()
{
    int t;
    scanf("%i", &t);
    for(int a0 = 0; a0 < t; a0++)
    {
        char* s = (char *)malloc(512000 * sizeof(char));
        scanf("%s", s);
        char* result = isBalanced(s);
        printf("%s\n", result);
    }
    return 0;
} 

0 个答案:

没有答案