20. Valid Parentheses
自認寫的有點鳥... 再想想看
題目原文
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
解題思路
程式解答
class Solution
{
public:
bool isValid(string s)
{
std::stack<char> p;
char temp;
if (s.length() % 2 != 0)
return false;
for (int i = 0; i < s.length(); i++)
{
switch (s[i])
{
case '(':
case '[':
case '{':
p.push(s[i]);
break;
case ')':
if (!p.size())
return false;
temp = p.top();
p.pop();
if (temp != '(')
return false;
break;
case ']':
if (!p.size())
return false;
temp = p.top();
p.pop();
if (temp != '[')
return false;
break;
case '}':
if (!p.size())
return false;
temp = p.top();
p.pop();
if (temp != '{')
return false;
break;
}
}
if (!p.size())
return true;
return false;
}
};
Last updated
Was this helpful?