
나의 풀이
import java.util.*;
class Solution {
boolean solution(String s) {
boolean answer = true;
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) { // 1
if (c == '(') stack.push(c);
else if (stack.empty()) return false;
else stack.pop();
}
return answer = stack.isEmpty(); // 2
}
}
과정
- 문자열 s의 문자를 하나씩 돌며 c가 '('이면 stack에 넣어주고, 비어있으면 거짓, ')'이면 stack에서 빼준다
- stack이 빈 stack이 아니라면 false
다른 사람 풀이
class Solution {
boolean solution(String s) {
boolean answer = false;
int count = 0;
for(int i = 0; i<s.length();i++){
if(s.charAt(i) == '('){
count++;
}
if(s.charAt(i) == ')'){
count--;
}
if(count < 0){
break;
}
}
if(count == 0){
answer = true;
}
return answer;
}
}