Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
20 changes: 20 additions & 0 deletions redandsilver/easy/ValidParentheses.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(char c : s){
if(c=='(' || c=='{' || c=='['){
st.push(c);
}else{
if (st.empty() ||
(c == ')' && st.top() != '(') ||
(c == '}' && st.top() != '{') ||
(c == ']' && st.top() != '[')) {
return false;
}
st.pop();
}
}
return st.empty();
}
};
23 changes: 23 additions & 0 deletions redandsilver/easy/ValidParentheses_2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution {
public:
bool isValid(string s) {
unordered_map<char,char> map;
Copy link
Collaborator

Choose a reason for hiding this comment

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

map을 사용했을 때와
스택으로 넣었을 때 메모리 차이가 어떤가요?

map 을 사용 안하고 스택에 괄호를 반대로 넣는건 어떤가요?if (c == '(' ) st.push(')') 이런 식입니다.

Copy link
Collaborator Author

@redandsilver redandsilver Apr 17, 2024

Choose a reason for hiding this comment

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

image
1MB 차이가 납니다.

map을 사용 안한 방식(Solution2)은 현택님이 하신것과 동일한 방법같아요..! 저는 열린 괄호와 닫힌 괄호가 상응하는지 비교했고 현택님은 열린괄호를 넣을 때 닫힌 괄호도 같이 넣음으로써 닫힌괄호가 같은지 비교하신듯요..!
근데 그렇게 하면 괄호가 많아지면 스택에 쌓이는 괄호들이 많아지지 않을까요???

Copy link
Collaborator

Choose a reason for hiding this comment

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

괄호가 스택에 많이 쌓이는 건 어차피 다른것들도 마찬가지 아닐까요??

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

제방법은 닫힌괄호를 넣지 않고 이미 넣어진 열린괄호를 pop 시켜줍니다..!!!

Copy link
Collaborator

Choose a reason for hiding this comment

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

아 제말은 순회하면서 열린괄호가 나오면 닫힌괄호를 스택에 넣고
순회하면서 닫힌 괄호가 나오면 pop해서 비교하는 방식을 이야기 한겁니다!

map['('] =')';
map['{'] ='}';
map['['] =']';

stack<char> st;
for(char c : s){
if(c=='(' || c=='{' || c=='['){
st.push(c);
}else{
if(st.empty() ||
map[st.top()] != c){
return false;
}
st.pop();
}
}
return st.empty();
}
};