https://leetcode.com/problems/valid-parentheses/
배열을 stack의 관점으로 보고 풀어도 되고, stack으로 풀어도 된다. 그 접근법을 사용하자.
괄호가 열렸다 닫히는 규칙이 있으면 stack으로 푸는게 좋다.
Input: s = "(]"
Output: false
Input: s = "()"
Output: true
class Solution {
public:
bool isValid(string s) {
std::stack<char> temp;
for (int i= 0; i < s.size(); ++i)
{
switch (s[i])
{
case '(':
temp.push('(');
break;
case '{':
temp.push('{');
break;
case '[':
temp.push('[');
break;
default:
break;
}
if (s[i] == ')' || s[i] == '}' || s[i] == ']')
{
if (temp.empty())
return false;
else if (temp.top() == '(' && s[i] == ')')
{
temp.pop();
}
else if (temp.top() == '{' && s[i] == '}')
{
temp.pop();
}
else if (temp.top() == '[' && s[i] == ']')
{
temp.pop();
}
else
return false;
}
}
if (temp.empty())
return true;
else
return false;
}
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Valid Parentheses.
Memory Usage: 6.3 MB, less than 58.60% of C++ online submissions for Valid Parentheses.