문제
A string is a valid parentheses string (denoted VPS)
We can similarly define the nesting depth depth(S) of any VPS S
Given a VPS represented as string s, return the nesting depth of s.
괄호, 숫자, 연산자로 이루어진 문자열이 주어졌을 때, 괄호의 최대 깊이를 구하는 문제이다.예를 들면 "()"의 깊이는 1, "(((8)))"의 깊이는 3, "(1+(2*3)+((8)/4))+1"의 깊이는 3이다.
풀이
아이디어
문자열을 앞에서부터 살펴보며 열린괄호가 나왔을 때는 깊어지고 닫힌괄호가 나왔을 때는 얕아지는 것으로 생각
코드
class Solution:
def maxDepth(self, s: str) -> int:
answer = 0
depth = 0
for c in s:
# 깊어짐
if c == "(":
depth += 1
answer = max([answer, depth])
# 얕아짐
elif c == ")":
depth -= 1
return answer
후기
난이도
문제 이해도 쉽고 아이디어를 떠올리기도 쉽고 구현도 쉬운 문제였다.
또한, 주어지는 문자열이 완전한 괄호형태(VPS)라 예외사항이 없어 까다롭지 않았다.
다른 풀이
answer을 최댓값으로 매번 갱신하는게 아니라 리스트에 담아 마지막에 최댓값을 반환할 수 있다.
'Algorithm' 카테고리의 다른 글
[LeetCode] 1544. Make The String Great (Daily Question) (0) | 2024.04.05 |
---|---|
[LeetCode] 1111. Maximum Nesting Depth of Two Valid Parentheses Strings (0) | 2024.04.04 |
[LeetCode] 79. Word Search (Daily Question) (0) | 2024.04.03 |
[LeetCode] 12. Integer to Roman (0) | 2024.04.02 |
[LeetCode] 205. Isomorphic Strings (Daily Question) (1) | 2024.04.02 |