题目描述:
给定一个字符串所表示的括号序列,包含以下字符: '(', ')'
, '{'
, '}'
, '['
and ']'
, 判定是否是有效的括号序列。
样例
括号必须依照 "()"
顺序表示, "()[]{}"
是有效的括号,但 "([)]"
则是无效的括号。
第一种 迭代
代码量少,很清晰易懂。
char string[] = "()[){}";
bool isCan= true;
for (int i = 0; i<6; i++) {
if (string[i] == '(' && string[i+1] == ')') {
i++;
} else if (string[i] == '[' && string[i+1] == ']') {
i++;
} else if (string[i] == '{' && string[i+1] == '}') {
i++;
} else {
isCan = false;
break;
}
}
利用栈后进先出的原则,如果当前字符等于'('或者'['或者'{'则入栈,否则则出栈做判断,如果不成对匹配则false。
如果有对栈的定义以及操作不是很熟悉的,可以看我之前写的博客栈和队列
代码实现:
#include <iostream>
#include <string>
using namespace std;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct {
ElemType *base;
ElemType *top;
int stackSize;
} Stack;
void initStack(Stack *st){
st->base = (ElemType *)malloc(sizeof(ElemType));
if(!st->base) exit(-1);//内存分配失败
st->top = st->base;
st->stackSize = STACK_INIT_SIZE;
}
void push(Stack *st,ElemType value){
long size = st->top-st->base;
if(st->top-st->base>st->stackSize)
{
st->base = (ElemType *)realloc(st->base, (st->stackSize +STACKINCREMENT) * sizeof(ElemType));
if (!st->base) {
exit(0);
}
st->stackSize = st->stackSize + STACKINCREMENT;
}
*st->top = value;
st->top++;
}
char pop(Stack *st) {
if (st->base == st->top) {
return NULL;
}
char temp = *(--st->top);
return temp;
}
int main(int argc, const char * argv[]) {
// insert code here...
Stack * st = (Stack *)malloc(sizeof(Stack*));
initStack(st);
char string[] = "()[){}";
bool isLegal = true;
for (int i = 0; i<6; i++) {
if (string[i] == '(' || string[i] == '[' || string[i] == '{') {
push(st, string[i]);
} else if (string[i] == ')'){
if (pop(st) != '(') {
isLegal = false;
break;
}
} else if (string[i] == ']'){
if (pop(st) != '[') {
isLegal = false;
break;
}
} else if (string[i] == '}'){
if (pop(st) != '{') {
isLegal = false;
}
}
}
return 0;
}