Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions valid-parentheses/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// TC: O(n)
// -> n = s.length
// SC: O(n)
// -> n = s.length / 2
Comment on lines +3 to +4
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

공간복잡도를 왜 이렇게 생각하셨는지 설명 부탁드려도 될까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

stack에 데이터가 들어가는 경우는 현재 값이 (, {, [ 인 경우 뿐이고, 최악의 경우(((({{{[[[ 같은 값이 주어지더라도, 여전히 상수값이기에 공간 복잡도는 O(n)이라고 생각합니다!

Copy link
Contributor

@obzva obzva Sep 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

답변 감사합니다 토니님 :)

O(N)의 형태로 사용 공간이 증가한다는 것은 이해 및 동의합니다

여전히 제가 이해를 하지 못한 부분이 있어서 더 질문 드리고 싶습니다

  1. n = s.length / 2 이 부분에 대해서 더 자세히 설명 부탁 드려도 될까요?

  2. 최악의 경우(((({{{[[[ 같은 값이 주어지더라도, 여전히 상수값에서 상수값이라는 표현에 대해 잘 이해하지 못했습니다. 1 <= s.length <= 10^4이라는 입력값 제한 조건이 있는데, 이 중에서 10^4를 상수라고 표현하신 걸까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@obzva 스택은 열린 괄호가 들어올 때마다 저장되고 닫힌 괄호가 들어올 때 제거되므로, 스택의 최대 크기는 열린 괄호의 개수만큼이 될겁니다. 따라서, 공간 복잡도는 최악의 경우 O( s.length() / 2) 라고 생각되지만 공간 복잡도계산시 보통 상수를 무시하므로 O(n) 이라고 생각합니다.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하 감사합니다 ㅎㅎㅎ
그치만 s 자체가 ((((((((((((((((((((((((((((((같은 값이 주어진다면 최악의 경우엔 공간 사용량이 s.length() / 2가 아닌 s.length() 아닌가요? 결국 아무 char도 pop되지 않고 스택에 쌓이기만 할테니까요

class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();

for (char c : s.toCharArray()) {
if (c == '(') stack.add(')');
else if (c == '{') stack.add('}');
else if (c == '[') stack.add(']');
else if (stack.isEmpty() || stack.pop() != c) return false;
}

return stack.isEmpty();
}
}