코드굽는 타자기
SWEA[1218] - 타일 장식물[D4] 본문
링크
SWEA[1218]
문제설명
- 괄호 짝짓기
문제풀이
- Stack - push&pop
문제코드
import java.io.FileInputStream;
import java.util.Scanner;
import java.util.Stack;
public class Solution1218 {
public static void main(String args[]) throws Exception
{
//System.setIn(new FileInputStream("res/swea/1218.txt"));
Scanner sc = new Scanner(System.in);
int T;
T=10;
for(int test_case = 1; test_case <= T; test_case++)
{
int ans=0;
int N = sc.nextInt();
sc.nextLine();
String line = sc.nextLine();
char[] words = line.toCharArray();
Stack<Character> stack = new Stack<Character>();
/*
* () <> [] {}
*/
for (int i = 0; i < words.length; i++) {
if(words[i]=='('||words[i]=='<'||words[i]=='['||words[i]=='{') {
stack.push(words[i]);
}
else if(words[i]==')'){
if(!stack.isEmpty()) {
if(stack.peek()=='(') {
stack.pop();
}
else {
stack.push(words[i]);
break;
}
}
else {
stack.push(words[i]);
break;
}
}
else if(words[i]=='>'){
if(!stack.isEmpty()) {
if(stack.peek()=='<') {
stack.pop();
}
else {
stack.push(words[i]);
break;
}
}
else {
stack.push(words[i]);
break;
}
}
else if(words[i]==']'){
if(!stack.isEmpty()) {
if(stack.peek()=='[') {
stack.pop();
}
else {
stack.push(words[i]);
break;
}
}
else {
stack.push(words[i]);
break;
}
}
else if(words[i]=='}'){
if(!stack.isEmpty()) {
if(stack.peek()=='{') {
stack.pop();
}
else {
stack.push(words[i]);
break;
}
}
else {
stack.push(words[i]);
break;
}
}
else continue;
}
if(stack.isEmpty())ans=1;
System.out.printf("#%d %d\n",test_case,ans);
}
}
}
아쉬운점
- str.split()으로 String배열 만듬
- str.toCharArray() 사용하면 char 배열 만들 수 있음.
- 닫는괄호 착각해서 pop 못했었음
잘한점
- Stack 사용
'알고리즘 > 스택&큐' 카테고리의 다른 글
SWEA[1229] - 암호문2[D3] (0) | 2020.02.04 |
---|---|
SWEA[1228] - 암호문1[D3] (0) | 2020.02.03 |
SWEA[1225] - 암호생성기[D3] (0) | 2020.02.03 |
Jungol[1141] - 불쾌한 날(Bad Hair Day) (0) | 2020.02.03 |
Comments