趣味算法-括号匹配
2012-01-23 12:30
375 查看
趣味算法-括号匹配:
用堆栈保存括号信息,遇左侧括号入栈,遇右侧并与栈顶的括号匹配出栈,继续扫描字符串。
算法复杂度分析:
时间复杂度 :O (n),扫描一次便能确定是否为字符串匹配。
用堆栈保存括号信息,遇左侧括号入栈,遇右侧并与栈顶的括号匹配出栈,继续扫描字符串。
#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++
- 括号匹配算法的java实现
- 顺序栈 & 顺序栈的括号匹配算法
- 算法分析——括号匹配
- 【算法】 括号匹配(二)
- 括号匹配算法
- 面试算法:使用堆栈判断括号的匹配
- 最小括号匹配算法(2013小米笔试)
- 机试算法讲解: 第13题 栈之括号匹配
- 括号匹配算法
- 括号匹配算法的栈实现
- 算法--括号匹配
- 利用栈实现括号匹配算法!
- 堆栈数据结构应用之括号匹配检查(算法3.2.2)
- 关于栈的算法(以括号匹配为例)
- imooc数据结构探险-栈篇 栈应用括号匹配二 由群友启发改良james_yuan老师算法
- [算法基础练习]最长括号匹配
- C语言实现括号匹配,中缀表达式转后缀表达式并计算的算法
- C/C++数据结构通过顺序栈实现括号()匹配算法
- 算法学习——栈的应用之括号匹配