4949번: 균형잡힌 세상
각 문자열은 마지막 글자를 제외하고 영문 알파벳, 공백, 소괄호("( )"), 대괄호("[ ]")로 이루어져 있으며, 온점(".")으로 끝나고, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마지막에
www.acmicpc.net
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
Stack<Character> stack = new Stack<>();
while (true) {
str = br.readLine();
if (str.equals(".")) {
break;
}
boolean flag = true;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '(' || ch == '[') {
stack.push(ch);
} else if (ch == ')' || ch == ']') {
if (stack.isEmpty() || !isMatchingPair(stack.peek(), ch)) {
flag = false;
break;
}
stack.pop();
}
}
if (!stack.isEmpty()) {
flag = false;
}
System.out.println(flag ? "yes" : "no");
stack.clear();
}
}
private static boolean isMatchingPair(char left, char right) {
return (left == '(' && right == ')') || (left == '[' && right == ']');
}
}
깨달은 점:
조건문이나 반복문에서 중복이 된다면 변수로 선언 또는 함수로 선언하여 처리하면 가독성이 좋아짐
'Java > AlgorithmPS' 카테고리의 다른 글
백준) 카드2(2164 번) (0) | 2023.10.12 |
---|---|
프로그래머스) 올바른 괄호 (0) | 2023.10.05 |
백준) 도키도키 간식드리미 (12789번) (0) | 2023.09.27 |
백준) 괄호 (9012번) (0) | 2023.09.26 |
백준) 좋은 단어(3986번) - 복습 필요 (0) | 2023.09.23 |