기본 틀 :
using System;
public class Solution {
public int solution(string s) {
int answer = -1;
return answer;
}
}
먼저 매개변수로 주어진 s를 회전시켜야 했다.
그래서 반복문과 Substring을 사용해서
currentString = currentString.Substring(1) + currentString[0];
위와 같은 방식으로 회전시켜줬다.
그 다음 문제를 잘 보면 '[', '{', '(' 괄호들은 중복돼서 나와도 되지만
향후 ']', '}', ')' 괄호가 나타났을 때 매칭이 확인을 해야하기 때문에
Stack을 사용해서 저장하기로 했다.
만약, ']', '}', ')' 괄호가 왔을 때 매칭이 안 될 경우 bool 값을 false로 해서
count가 1증가하지 않도록 만들어 줬다.
using System;
using System.Collections.Generic;
public class Solution {
public int solution(string s)
{
if(s.Length % 2 == 1) return 0;
Stack<char> stack = new Stack<char>();
int count = 0;
string currentString = s;
for (int i = 0; i < s.Length; i++)
{
bool check = true;
stack.Clear();
for(int j = 0; j < currentString.Length; j++)
{
if(currentString[j] == '[' || currentString[j] == '{' || currentString[j] == '(')
stack.Push(currentString[j]);
else
{
if (stack.Count == 0)
{
check = false;
break;
}
char open = stack.Pop();
if(open == '[' && currentString[j] == ']') continue;
else if(open == '{' && currentString[j] == '}') continue;
else if(open == '(' && currentString[j] == ')') continue;
check = false;
break;
}
}
if(check) count++;
currentString = currentString.Substring(1) + currentString[0];
}
return count;
}
}
'문제 풀기 > C#' 카테고리의 다른 글
86. H-index (0) | 2025.03.06 |
---|---|
85. 연속 부분 수열 합의 개수 (0) | 2025.03.04 |
83. 귤 고르기 (Dictionary 요소 정렬) (0) | 2025.03.04 |
82. 멀리 뛰기 (0) | 2025.02.28 |
81. N개의 최소공배수 (0) | 2025.02.28 |