Skip to content

Comments

redandsilver-6#34

Open
redandsilver wants to merge 1 commit intomainfrom
redandsilver
Open

redandsilver-6#34
redandsilver wants to merge 1 commit intomainfrom
redandsilver

Conversation

@redandsilver
Copy link
Collaborator

Valid Parentheses

괄호가 유효한지 판단하는 문제이다.

  • 괄호는 같은 타입의 괄호로만 닫히고 열린괄호는 이에 상응하는 닫힌 괄호가 있다.
    () -> closed
    {} -> closed
    [] -> closed

  • 열린 괄호는 옳은 순서로 닫힌다.
    ({})-> closed
    {(})-> not closed

Approach

스택에 괄호를 입력받은 순서대로 넣는다.
스택이 비어있는데 닫힌 괄호라면 -> false
스택의 top과 입력받은 괄호가 상응한다면 -> pop
그렇지 않다면 -> false
입력이 끝난 후 스택에 요소가 남아있다면 괄호가 짝지어지지 않았다는 뜻이므로 -> false

Code

Solution 1

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();

Solution 2

if 문에 조건을 다는것이 번거로워
괄호를 unordered_map 을 이용해서 해보았다.

unordered_map<char,char> map;
      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();

@redandsilver redandsilver added the coding test 코딩테스트 라벨 label Apr 16, 2024
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해서 비교하는 방식을 이야기 한겁니다!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coding test 코딩테스트 라벨

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants