난이도
실버 I
풀이
자바 풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Math;
public class Main{
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
String arr = br.readLine();
int result = 0;
int min_value = 0;
for(int idx = 0; idx< arr.length(); idx++){
if(arr.charAt(idx)=='('){
result+=1;
}else{
result-=1;
}
if(Math.abs(result)>min_value){
min_value = Math.abs(result);
}
}
if(result==0){
System.out.println(min_value);
}else{
System.out.println(-1);
}
}
}
파이썬 풀이
import sys
input=sys.stdin.readline
N=int(input())
bracket=input().rstrip()
result=0
cnt=0
for bra in bracket:
if bra=='(':
cnt+=1
elif bra==')':
cnt-=1
if abs(cnt)>result:
result=abs(cnt)
if cnt==0:
print(result)
else:
print(-1)
문제 링크
https://www.acmicpc.net/problem/25918
25918번: 북극곰은 괄호를 찢어
극지 연구소에서 연구 중인 협이는 새로운 북극곰의 특성을 발견했다. 그것은 바로 북극곰이 $O$와 $X$를 보면 $()$와 $)($로 찢어버린다는 것이다. 협이는 이러한 북극곰의 특성을 이용하여 길이 $N
www.acmicpc.net
'알고리즘' 카테고리의 다른 글
프로그래머스 크기가 작은 문자열 (자바, 파이썬 풀이) (0) | 2023.04.24 |
---|---|
프로그래머스 테이블 해시 함수 (0) | 2023.04.24 |
프로그래머스 크기가 작은 부분 문자열 (0) | 2023.04.21 |
프로그래머스 신규 아이디 추천 (0) | 2023.04.20 |
백준 치즈 (2636번) (0) | 2023.04.20 |