문제
- ’(’, ’)’, ’{’, ’}’, ’[’, ’]‘의 determine 이 주어졌을때, 모든 bracket 들이 순서에 맞게 잘 닫혔는지 확인
public class Solution {
public static void main(String[] args) {
System.out.println(isValid("()"));
System.out.println(isValid("()[]{}"));
System.out.println(isValid("(]"));
System.out.println(isValid("((())"));
System.out.println(isValid("("));
}
public static boolean isValid(String s) {
}
}
결과 및 풀이
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
Map<Character, Character> closeDetermineMap = Map.of(
')', '(',
']', '[',
'}', '{'
);
for (char c : s.toCharArray()) {
Character closed = closeDetermineMap.get(c);
if(closed == null) {
stack.push(c);
} else {
if (stack.isEmpty() || closed != stack.pop()) {
return false;
}
}
}
if (!stack.isEmpty()) {
return false;
}
return true;
}
배웠다
- if 문으로 남발하지 말고, 조건에 hashmap을 사용할 수 있는지 확인을 먼저 해보자.