231111 괄호 회전하기

Jongleee·2023년 11월 18일
0

TIL

목록 보기
414/737
public int solution(String s) {
	int answer = 0;
	for (int i = 0; i < s.length(); i++) {
		StringBuilder sb = new StringBuilder(s);
		String substring = s.substring(0, i);
		sb.delete(0, i);
		sb.append(substring);
		if (isCorrect(sb.toString())) {
			answer += 1;
		}
	}

	return answer;
}

private boolean isCorrect(String s) {
	Stack<Character> stack = new Stack<>();
	for (char c : s.toCharArray()) {
		if (stack.isEmpty()) {
			stack.push(c);
		} else {
			switch (c) {
				case ']':
					popCondition(stack, '[');
					break;
				case '}':
					popCondition(stack, '{');
					break;
				case ')':
					popCondition(stack, '(');
					break;
				default:
					stack.push(c);
			}
		}
	}
	return stack.isEmpty();
}

private void popCondition(Stack<Character> stack, char openingBracket) {
	if (!stack.isEmpty() && stack.peek() == openingBracket) {
		stack.pop();
	} else {
		stack.push(openingBracket == '(' ? ')' : (openingBracket == '{' ? '}' : ']'));
	}
}

출처:https://school.programmers.co.kr/learn/courses/30/lessons/76502

0개의 댓글