CodeWars 마흔 일곱 번째 문제
Updated:
Valid Braces
public boolean isValid(String braces) {
String validBrace = "(\\(\\))|(\\{\\})|(\\[\\])";
String beforeBraces = braces;
do {
beforeBraces = braces;
braces = braces.replaceAll(validBrace , "");
} while(beforeBraces.length() > braces.length());
return braces.length() == 0;
}
- 내가 접근 했던 방식은 정규표현식을 이용해서 (), {}, [] 패턴을 찾으면 삭제처리(replace) 후 최종적으로 braces의 길이를 확인하여 리턴하는 방식이었다.
- 정규표현식이 익숙치가 않아서 위의 방식을 찾는데 애를 많이 먹었다….ㅠ
- 문제는 match를 이용해서 while의 조건을 걸라고 했는데 잘 안되어서 어쩔 수없이 문자열을 비교하였다…
- best코드의 경우 push pop을 하여 접근 하는 방식이 있었고 다른건 나랑 같이 replace를 통해 풀었다.
public boolean isValid(String braces) {
Stack<Character> s = new Stack<>();
for (char c : braces.toCharArray())
if (s.size() > 0 && isClosing(s.peek(), c)) s.pop();
else s.push(c);
return s.size() == 0;
}
public boolean isClosing(char x, char c) {
return (x == '{' && c == '}') || (x == '(' && c == ')') || (x == '[' && c == ']');
}
public boolean isValid(String s) {
String lastIteration = s;
String currentIteration = s;
do {
lastIteration = currentIteration;
currentIteration = lastIteration.replace("[]" , "").replace("{}", "").replace("()" , "");
} while(currentIteration.length() < lastIteration.length());
return currentIteration.equals("");
}