250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code c++)Valid Parentheses 본문
728x90
반응형
20. Valid Parentheses
Given a string s 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.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}" Output: true
Example 3:
Input: s = "(]" Output: false
Example 4:
Input: s = "([)]" Output: false
Example 5:
Input: s = "{[]}" Output: true
Constraints:
- 1 <= s.length <= 104
- s consists of parentheses only '()[]{}'.
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for(int i = 0; i < s.size(); i++){
if(stk.empty()){
stk.push(s[i]);
}
else{
if(s[i] == ')'){
if(stk.top() == '('){
stk.pop();
}
else{
stk.push(s[i]);
}
}
else if(s[i] == '}'){
if(stk.top() == '{'){
stk.pop();
}
else{
stk.push(s[i]);
}
}
else if(s[i] == ']'){
if(stk.top() == '['){
stk.pop();
}
else{
stk.push(s[i]);
}
}
else{
stk.push(s[i]);
}
}
}
if(stk.empty()){
return true;
}
else{
return false;
}
}
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)Remove Duplicates from Sorted Array (0) | 2021.07.07 |
---|---|
(Leet Code c++)Merge Two Sorted Lists (0) | 2021.07.07 |
(Leet Code c++)Longest Common Prefix (0) | 2021.07.06 |
(Leet Code c++)Roman to Integer (0) | 2021.07.06 |
(Leet Code c++)Palindrome Number (0) | 2021.07.06 |