괄호는 가장 뒤의 '(' 가 가장 먼저 나오는 ')'와 짝이라서 ')'가 입력되면 가장 나중에 입력된 '(' 가 pop 되어야 한다
어떤 경우에 NO를 출력하고, 어떤 경우에 YES를 출력해야 하는지 케이스를 나눠서 알고리즘 생각하기!
<C++>
#include <iostream>
#include <stack>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin>>n;
for(int i=0;i<n;i++){
stack<char> st;
string state="YES";
string input;
cin>>input;
for(int j=0;j<input.length();j++)
{
if(input[j]=='(')
st.push(input[0]);
else if(input[j]==')'){
if(st.empty()){
state="NO";
break;}
else
st.pop();
}
}
if(st.empty())
cout<<state<<'\n';
else
cout<<"NO"<<'\n';}
return 0;
}
<Java>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
Stack<Character> stack = new Stack<>();
String state = "YES";
String input = br.readLine();
for (int j = 0; j < input.length(); j++) {
if (input.charAt(j) == '(')
stack.push(input.charAt(0));
else if (input.charAt(j) == ')') {
if (stack.isEmpty()) {
state = "NO";
break;
} else {
stack.pop();
}
}
}
if (stack.isEmpty())
System.out.println(state);
else
System.out.println("NO");
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}