sleepyotter
Valid Parentheses 본문
괄호의 짝을 맞추는 문제. 간단하게 stack으로 여는 괄호면 넣고 닫는 괄호면 짝이 맞는지 확인한다. 주의할 점은 if에서 체크할 때 비어있는지 먼저 체크해야 한다. 안그러면 ch.top()을 통해 null을 보려고 하기 때문에 runtime에러가 발생한다. 0ms 6.4MB 사용. 같은 6.4MB사용해도 50% less than이 뜨는걸 보면 다들 반올림 정도의 오차정도만 있는거 같아서 더 최적화는 고려하지 않았다.
class Solution {
public:
bool isValid(string s) {
stack<char> ch;
for (int i = 0; i < s.size(); ++i)
{
switch (s[i]) {
case '(':
ch.push(s[i]);
break;
case '{':
ch.push(s[i]);
break;
case '[':
ch.push(s[i]);
break;
case ')':
if(ch.empty() || ch.top()!='(') return false;
ch.pop();
break;
case '}':
if (ch.empty() || ch.top() != '{') return false;
ch.pop();
break;
case ']':
if (ch.empty() || ch.top() != '[') return false;
ch.pop();
break;
}
}
if (!ch.empty()) return false;
return true;
}
};
'프로그래밍 > 알고리즘+코딩테스트' 카테고리의 다른 글
Remove Duplicates from Sorted Array (0) | 2021.08.26 |
---|---|
Merge Two Sorted Lists (0) | 2021.08.24 |
Longest Common Prefix (0) | 2021.08.22 |
Roman To Integer (0) | 2021.08.22 |
Palindrome Number (0) | 2021.08.22 |