Machineboy空
Excercism - Matching Brackets 괄호닫기 본문
문제요약
괄호쌍이 제대로 닫히는 지 파악하라!
https://exercism.org/tracks/csharp/exercises/matching-brackets
Matching Brackets in C# on Exercism
Can you solve Matching Brackets in C#? Improve your C# skills with support from our world-class team of mentors.
exercism.org
난이도
Medium
풀이 포인트
- key - value를 사용하든, 두 괄호쌍의 연결해둘 수 있는 자료구조 사용
- Stack 아이디어
https://machineboy0.tistory.com/177
9012 : 괄호 - stack, 그리디 알고리즘, getline(cin,s)
https://www.acmicpc.net/problem/9012 9012번: 괄호 괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열
machineboy0.tistory.com
REVIEW
stack 문제네까지 파악하고 예전에 풀었던 문제들도 기억해 냈는데 결국 못풀었다. 바보다.
모범풀이 보니 정말 아이디어만 제대로 기억했어도 틀리지 않았을 기본적인(?)문제..
내가 시도했던 것은 아래의 경우도 true라고 판단해버리는
단순히 괄호의 쌍의 개수가 올바른지를 체크하는 코드였다.
[({]})
여튼 이제는 이해가 되었으니 다음에 풀이 보지 않고 무조건 맞추기.
CODE
using System;
using System.Collections.Generic;
public static class MatchingBrackets
{
public static bool IsPaired(string input)
{
Stack<char> stack = new Stack<char>();
Dictionary<char, char> matchingPairs = new Dictionary<char, char>
{
{ ']', '[' },
{ '}', '{' },
{ ')', '(' }
};
foreach (char c in input)
{
if (c == ' ') continue; // 공백 무시
if (matchingPairs.ContainsValue(c)) // 여는 괄호인지 확인
{
stack.Push(c);
}
else if (matchingPairs.ContainsKey(c)) // 닫는 괄호인지 확인
{
if (stack.Count == 0 || stack.Peek() != matchingPairs[c])
{
return false; // 스택이 비어 있거나 매칭되는 괄호가 없으면 false
}
stack.Pop(); // 올바른 짝이면 Pop()
}
}
return stack.Count == 0; // 스택이 비어 있으면 true (모든 괄호가 짝이 맞음)
}
}
'Computer > Coding Test' 카테고리의 다른 글
Excercism - Simple Cipher, 아스키 코드, 시저암호, 비젠네르 암호 (0) | 2025.02.26 |
---|---|
Excercism - Wordy 문자열 다루기, Split, Replace, int.tryParse (0) | 2025.02.20 |
Excercism - State of Tic-Tac-Toe (0) | 2025.02.17 |
Excercism - BookStore 조합 (1) | 2025.02.14 |
Exercism - Pascal's Triangle 파스칼 삼각형 (0) | 2025.02.13 |