题目:
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.
Subscribe to see which companies asked this question
Solution:
思路,联想到栈的使用,基本就解决了一半。
bool isValid(string s)
{
int n = s.size();
int i = 0;
stack<char> str;
while(i<n)
{
char ch = s[i];
if(ch == '(' || ch == '[' || ch == '{')
{
str.push(ch);
}
else
{
if(!str.empty())
{
char th = str.top();
str.pop();
if(!IsPair(th,ch))
return false;
}
else
return false;
}
i++;
}
if(str.size() != 0)
return false;
return true;
}
bool IsPair(char m,char n)
{
if(m == '(' && n == ')')
return true;
else if(m == '[' && n == ']')
return true;
else if(m == '{' && n == '}')
return true;
else
return false;
}