반응형
https://leetcode.com/problems/remove-outermost-parentheses/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
간단 구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
정답 변수 ans, 깊이 depth를 선언해줍니다.
📔 풀이과정
valid한 형태의 문자열이 들어오므로 s의 원소를 순회하며 바깥으로 감싸진 '()'가 있는지만 판단해 정답 변수 ans에 더해주면 됩니다. 더하는 경우의 수는 다음 두 가지입니다.
1. 열린 괄호가 나왔을 때 depth가 양수라면 안쪽 부분의 소괄호이므로 ans에 더해줍니다.
2. 닫힌 괄호가 나왔을 때 바깥에 소괄호가 있는 경우라면 ans에 더해줍니다.
📔 정답 출력 | 반환
ans를 반환해줍니다.
📕 Code
📔 C++
class Solution {
public:
string removeOuterParentheses(string s) {
int depth = 0;
string ans;
for(auto c : s) {
if(c == '(' && depth++ > 0) ans += c;
if(c == ')' && --depth > 0) ans += c;
}
return ans;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(SQL) - LeetCode (easy) 1068. Product Sales Analysis I (0) | 2023.10.20 |
---|---|
(C++) - LeetCode (easy) 1046. Last Stone Weight (0) | 2023.10.16 |
(C++) - LeetCode (easy) 1018. Binary Prefix Divisible By 5 (2) | 2023.10.05 |
(C++, Rust) - LeetCode (easy) 1013. Partition Array Into Three Parts With Equal Sum (0) | 2023.10.04 |
(C++, Rust) - LeetCode (easy) 1009. Complement of Base 10 Integer (0) | 2023.09.26 |