주녘공부일지

[프로그래머스 C#] Lv.2 괄호 회전하기 본문

Programmers - C#/CodingTest Lv.2

[프로그래머스 C#] Lv.2 괄호 회전하기

주녘 2023. 12. 4. 14:58
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/76502

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 정답코드 및 핵심 아이디어, 유의사항

문자열을 회전하며 올바른 괄호인지 체크하는 문제

 

1) 문자열을 회전- 문자열을 계속 추가, 삭제해야하므로 StringBuilder를 사용

 

2) 문자열이 주어진 조건에 따른 올바른 괄호인지 체크- 올바른 괄호는 결국 여는 괄호 순서의 역순으로 닫는 괄호가 나오면 됨 -> Stack(후입선출) 활용https://godgjwnsgur7.tistory.com/46

 

[C#] 자료구조 ( 제네릭 컬렉션 )

자료구조(Data Structure)란? 데이터를 효율적으로 접근하고 조작할 수 있게 데이터 구조를 만들어 관리하는 것 - Collections은 C#에서 지원하는 자료구조 클래스 using System.Collections.Generic; 제네릭 컬렉

godgjwnsgur7.tistory.com

    using System;
    using System.Collections.Generic;
    using System.Text;

    public class Solution
    {
        public int solution(string s)
        {
            int answer = 0;
            var sb = new StringBuilder(s);

            for (int i = 0; i < s.Length; i++)
            {
                // 올바른 문자열인지 체크
                if (Function(sb.ToString()))
                    answer++;

                // 회전
                sb.Append(sb[0]);
                sb.Remove(0, 1);
            }
            
            return answer;
        }

        // 올바른 괄호인지 판단하는 메서드
        public bool Function(string str)
        {
            // 개수가 홀수면 올바른 괄호일 수 없음 (테케 13 예외처리)
            if (str.Length % 2 == 1)
                return false;

            var stack = new Stack<Char>();

            for (int i = 0; i < str.Length; i++)
            {
                switch (str[i])
                {
                    case ')':
                        if (stack.Count == 0 || stack.Pop() != '(')
                            return false;
                        break;
                    case ']':
                        if (stack.Count == 0 || stack.Pop() != '[')
                            return false;
                        break;
                    case '}':
                        if (stack.Count == 0 || stack.Pop() != '{')
                            return false;
                        break;
                    default: // (, [, {
                        stack.Push(str[i]);
                        break;
                }
            }
            return true;
        }
    }
728x90