개요[ | ]
- HR자바 Java Stack
Java
Copy
import java.util.*;
class Solution{
public static void main(String []args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input=sc.next();
//Complete the code
System.out.println(isBalanced(input));
}
}
static boolean isBalanced(String str) {
Stack<Character> stack = new Stack<Character>();
for( int i=0; i<str.length(); i++ ) {
char ch = str.charAt(i);
if( ch == '(' || ch == '{' || ch == '[' ) {
stack.push(ch);
continue;
}
if( stack.empty() ) return false;
char last = stack.pop();
if( ch == ')' && last != '(' ) return false;
if( ch == '}' && last != '{' ) return false;
if( ch == ']' && last != '[' ) return false;
}
return stack.empty();
}
}
편집자 Jmnote Jmnote bot
로그인하시면 댓글을 쓸 수 있습니다.