1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.Collections.Generic;
 
public class Solution
{
    public int solution(string s)
    {
        int rightCount = 0;
        string shifted = s;
 
        while (true)
        {
            if (IsClosedChar(shifted[0]))
            {
                shifted = GetShiftedString(shifted);
            }
            else
            {
                if (IsMatching(shifted))
                    rightCount++;
 
                shifted = GetShiftedString(shifted);
            }
 
            if (shifted == s)
                break;
        }
 
        return rightCount;
    }
 
    private bool IsOpenChar(char c)
    {
        if (c == '[' || c == '{' || c == '(')
            return true;
 
        return false;
    }
 
    private bool IsClosedChar(char c)
    {
        return !IsOpenChar(c);
    }
 
    private char GetCloseChar(char c)
    {
        if (c == '[')
            return ']';
 
        if (c == '{')
            return '}';
 
        if (c == '(')
            return ')';
 
        return '_';
    }
 
    private string GetShiftedString(string s)
    {
        return s.Substring(1+ s[0];
    }
 
    private bool IsMatching(string s)
    {
        Stack<char> stack = new Stack<char>();
 
        for (int i = 0; i < s.Length; i++)
        {
            //열린 괄호를 스택에 넣는다.
            if (IsOpenChar(s[i]))
            {
                stack.Push(s[i]);
            }
            else //닫힌 괄호 체크..
            {
                //열린 괄호가 없는데 닫으면 false
                if (stack.Count == 0)
                    return false;
                
                //가장 마지막에 열린 괄호와 매칭되는지 검사
                if (GetCloseChar(stack.Peek()) == s[i])
                {
                    stack.Pop();
                }
                else
                {
                    return false;
                }
            }
        }
 
        //열린 괄호가 아예 없는 경우도 예외처리
        return stack.Count == 0;
    }
}
cs

+ Recent posts