1. 程式人生 > >#20 Valid Parentheses

#20 Valid Parentheses

ica ini content ng- height parent sta clas cas

題目鏈接:https://leetcode.com/problems/valid-parentheses/


Given a string containing just the characters ‘(‘, ‘)‘,‘{‘, ‘}‘, ‘[‘ and ‘]‘, determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]"

and "([)]" are not.

typedef struct StackRecord {    //不考慮溢棧實現簡單的堆棧
	char ch[100];
	int top;
}*Stack;
bool isEmpty(Stack stack) {
	if (stack->top >= 0)
		return false;
	return true;
}
Stack init() {
	Stack stack = (Stack)malloc(sizeof(struct StackRecord));
	stack->top = -1;
	return stack;
}
void push(char ch, Stack stack) {
	stack->ch[++stack->top] = ch;
}
char top(Stack stack) {     //返回棧頂元素,空棧時返回'\0'
    if(!isEmpty(stack))
	    return stack->ch[stack->top];
	return 0;
}
void pop(Stack stack) {
	--stack->top;
}
bool isValid(char* s) {
	Stack stack = init();
	while (*s) {
		switch (*s) {
		case '(':       //左括號入棧
		case '[':
		case '{':
			push(*s, stack);
			break;
		case ')':      //右括號。查看棧頂是否為相應左括號。

不是返回false;否則出棧 if (top(stack) != '(') return false; pop(stack); break; case ']': if (top(stack) != '[') return false; pop(stack); break; case '}': if (top(stack) != '{') return false; pop(stack); break; default: return false; } ++s; } if (!isEmpty(stack)) //棧內不空說明有多余左括號 return false; return true; }



#20 Valid Parentheses