Valid Parentheses
Total Accepted: 71209 Total Submissions: 265268 Difficulty: EasyGiven 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.
这道题我的实现方法很简单,而这应该也是成对括号问题的通用处理方法。即建立一个堆栈,然后遍历字符串如果遇到左括号’(‘,’[‘,’{‘,就入栈,如果遇到右括号’)’,’]’,’}’就看当前栈顶的元素,如果是与之匹配的左括号,那就让这个左括号出栈,否则,匹配就是错误的返回false,当数组都遍历一遍后,我们查看如果栈是否为空,如果为空,说明所有括号都得到匹配,返回true,否则返回false。
下面是完整代码:
#include <iostream>
#include <stdio.h>
using namespace std;
bool isValid(char* s)
{
int size = strlen(s);
char *stack = (char*)malloc(sizeof(char) * size);
int top = -1;
for(int i = 0; i < size; i++)
{
switch(s[i])
{
case '(': top++; stack[top] = '('; break;
case '{': top++; stack[top] = '{'; break;
case '[': top++; stack[top] = '['; break;
case ')':
{
if(top >=0 && stack[top] == '(')
top--;
else
return false;
break;
}
case '}':
{
if(top >=0 && stack[top] == '{')
top--;
else
return false;
break;
}
case ']':
{
if(top >=0 && stack[top] == '[')
top--;
else
return false;
break;
}
}
}
if(top == -1)
return true;
else
return false;
}
int main()
{
char s[100];
scanf("%s",s);
cout<<isValid(s)<<endl;
}