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.
题意:给一串只包含有’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 和’]’,的字符串,要求判定是否是合法的。
思路:这个很自然就能想到用栈,典型的栈应用,复杂度O(n)。
代码:
class Solution {
public:
bool isValid(string s) {
stack<char>ch;
int i,j;
int len=s.size();
for(i=0;i<len;i++)
{
if(s[i]=='('||s[i]=='{'||s[i]=='[')
ch.push(s[i]); //入栈
else
{
if(ch.empty())return false;
char temp=ch.top();
if((s[i]==')'&&temp=='(')||(s[i]==']'&&temp=='[')||(s[i]=='}'&&temp=='{'))
ch.pop(); //出栈
else return false;
}
}
if(ch.empty())return true;
else return false;
}
};