Open levi-yo opened 6 years ago
import java.util.ArrayList; import java.util.Iterator; import java.util.Scanner; import java.util.Stack;
public class Bracket { static String balance(String str){ Stack s=new Stack(); String str1="YES"; for(int i=0;i<str.length();i++){ if(str.charAt(i)=='('){ s.push(str.charAt(i)); }else if(str.charAt(i)==')' && !s.isEmpty() && s.peek().equals('(')){ s.pop(); }else if(s.isEmpty() && str.charAt(i)==')'){ str1="NO"; } } if(!s.isEmpty()) str1="NO"; return str1; } public static void main(String[] args) { // TODO Auto-generated method stub ArrayList list=new ArrayList(); Scanner sc=new Scanner(System.in); int n=Integer.parseInt(sc.nextLine()); for(int i=0;i<n;i++){ String str=sc.nextLine(); list.add(balance(str)); } Iterator it=list.iterator(); while(it.hasNext()) System.out.println(it.next()); } }
import java.util.ArrayList; import java.util.Scanner; import java.util.Stack;
public class Main { /*
알고리즘 분류. 스택 */ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
ArrayList<String> arr = new ArrayList<>();
for(int i=0; i<t; i++) {
arr.add(sc.next());
}
for(int i=0; i<arr.size();i++) {
findSolution(arr.get(i));
}
}
public static void findSolution(String s) {
Stack
st.push(s.charAt(0)); //첫글자는 조건없이 push
for(int i=1; i<s.length();i++) {
char c = s.charAt(i);
if(c=='(') {
st.push(c); //열린괄호는 스택에 push
}else{
if(!st.isEmpty() && st.peek() == '(') {
st.pop(); //'()'가 만들어지면 스택에서 pop함
}else {
st.push(c);
}
}
}
if(st.size() == 0) {
System.out.println("YES");
}else {
System.out.println("NO");
}
}
}
https://www.acmicpc.net/problem/9012