[leetcode] Valid Parentheses

来源:互联网 发布:淘宝客服能在家里做吗 编辑:程序博客网 时间:2024/06/15 07:36

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.

Solution:

This is a classical case for the usage of stack. 

1. when '(', '{' or '[', push into the stack.

2. otherwise, if the stack is empty, then occurs mismatching, return false. or, if the element in the top of the stack mismatch with s[i], then return false. otherwise pop the stack.

3. finally we should check if the stack is empty, if not, return false.

runtime:


source code:

bool isValid(string s) {stack<char> chstack;for(int i=0; i<s.size(); i++) {if(s[i] == '(' || s[i] == '[' || s[i] == '{') {chstack.push(s[i]);} else {if(chstack.empty()) { return false; }switch(s[i]) {case ']': if(chstack.top() != '[') {return false;} break;case '}':if(chstack.top() != '{') {return false;} break;case ')':if(chstack.top() != '(') {return false;} break;default :break;}chstack.pop();}}if( !chstack.empty() ) return false;else return true;}









0 0