반응형
https://school.programmers.co.kr/learn/courses/30/lessons/12909
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
Queue 사용
import java.util.*;
class Solution {
boolean solution(String s) {
boolean answer = true;
char[] arr = s.toCharArray();
Queue<Character> queue = new LinkedList<>();
for(char c : arr){
if(c == '('){
queue.offer(c);
} else {
if(queue.isEmpty()) return false;
queue.poll();
}
}
return queue.isEmpty();
}
}
charAt() 사용
class Solution {
boolean solution(String s) {
int count = 0;
int len = s.length(); // 반복문 안에서 매번 호출하지 않도록 미리 변수화
for (int i = 0; i < len; i++) {
if (s.charAt(i) == '(') {
count++;
} else {
// 닫는 괄호가 나왔는데 열린 괄호가 없다면 바로 false
if (count == 0) return false;
count--;
}
}
// 최종적으로 모든 괄호의 짝이 맞아서 0이 되어야 true
return count == 0;
}
}반응형
'코딩테스트' 카테고리의 다른 글
| [프로그래머스/Java] K번째수 : Arrays.copyOfRange() (0) | 2026.07.14 |
|---|---|
| [프로그래머스/Java] 프로세스 Queue (+PriorityQueue) (0) | 2026.07.13 |
| [프로그래머스/Java] 기능개발 (0) | 2026.07.13 |
| [프로그래머스/Java] 게임 맵 최단거리 (BFS) (0) | 2026.07.10 |
| BFS 공부 - 최단 거리 (최소 시간) (0) | 2026.07.10 |