趣味算法-括号匹配

趣味算法-括号匹配:

用堆栈保存括号信息,遇左侧括号入栈,遇右侧并与栈顶的括号匹配出栈,继续扫描字符串。


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


// using stack to save and judge the string
// return the index where the bracket not match
// return 0 no problem
int IsMatch(char* strTest, int nLen)
{
    char* pStack = NULL;
    char* pChr = strTest;
    int   i = 0;
    int   nStackIdx = 0;


    if ((pChr == NULL) || (nLen == 0))
    {
        return -1;
    }
    pStack = (char*) malloc(sizeof(char)*nLen);


    if (pStack == NULL)
    {
        return -1;
    }


    while (i < nLen)
    {
        switch(*pChr)
        {
        case '{':
        case '[':
        case '(':
        case '<':
            pStack[nStackIdx] = *pChr;
            nStackIdx++;
            break;


        case '}':
            if ((nStackIdx > 0) && (pStack[nStackIdx-1] == '{'))
            {
                nStackIdx--;
            }
            else
            {
                printf("Miss mathc } at %d\n", i+1);
                return i+1;
            }
            break;
        case ']':
            if ((nStackIdx > 0) && (pStack[nStackIdx-1] == '['))
            {
                nStackIdx--;
            }
            else
            {
                printf("Miss mathc ] at %d\n", i+1);
                return i+1;
            }
            break;
        case ')':
            if ((nStackIdx > 0) && (pStack[nStackIdx-1] == '('))
            {
                nStackIdx--;
            }
            else
            {
                printf("Miss match ) at %d\n", i+1);
                return i;
            }
            break;
        case '>':
            if ((nStackIdx > 0) && (pStack[nStackIdx-1] == '<'))
            {
                nStackIdx--;
            }
            else
            {
                printf("Miss match > at %d\n", i+1);
                return i;
            }
            break;
        default:
            break;
        }
        i++;
        pChr++;
    }
    if (nStackIdx == 0)
        printf("The string: %s is ok\n", strTest);
    else
        printf("The string is not bracket match: missing %c at %d\n", 
               pStack[nStackIdx-1], nStackIdx);


    free(pStack);
    return nStackIdx;
}


int main()
{
    char sTestOk[] = "{<[<<{{{[<<>>[[]]]}}}>>]>}";
    char sTestFail[] = "{";
    char sTestFail1[] = "<<{[(asdfe]]}>>";
    int i = 0;
    IsMatch(sTestOk, strlen(sTestOk));
    IsMatch(sTestFail, strlen(sTestFail));
    IsMatch(sTestFail1, strlen(sTestFail1));
    scanf("%d", &i);
    return 0;
}


算法复杂度分析:

时间复杂度 :O (n),扫描一次便能确定是否为字符串匹配。











你可能感兴趣的:(c,算法,String,null)