본격적으로 DFS, BFS 알고리즘을 시작하기전 스택과 큐부터 꼼꼼히 공부해야겠다고 생각해서 시작했다!
스택 -> DFS -> 큐 -> BFS 순서로 공부하리라!
백준 10828 스택문제는 알고리즘 수업시간에도 스택을 다뤘어서 그렇게 어려운 난이도는 아니었다!
하지만 명확하게 기억나지 않는 몇 가지들이 있어 문제풀면서 사용한 문자열 메소드, scanner 메소드 등을 모두 정리해보자
String.equals() | 문자열이 같은지 확인해준다 |
String.length() | 문자열 길이를 반환한다 |
String.split() | 큰 따옴표 안에 들어가는 문자로 문자열을 구분자로 문자열을 구분하여 배열로 리턴한다. 구분자를 입력하지 않으면 공백이 기본이다. |
Scanner.next() | 문자열을 띄어쓰기로 구분하여 입력받는다. |
Scnnaer.nextLine() | 문자열을 엔터키로 구분하여 입력받는다. |
처음에 제출했을때는 시간초과가 나서 당황했다(ㄴㅇㄱ!)
그래서 BufferedReader를 써보기로 했다.
BufferedReader를 쓰려면
1. java.io를 import 해야하고
2. try-catch문을 꼭 써주어야한다.
그리고 BuffeedrReader에서 readLine을 이용해서 nextLine처럼 문자열을 한 줄씩 입력받을 수 있다.
read를 사용하면 문자를 하나씩 입력받을 수 있다고하는데 출력은 int타입이다.
-> 더알아보기!
BufferedReader (Java SE 17 & JDK 17)
All Implemented Interfaces: Closeable, AutoCloseable, Readable Direct Known Subclasses: LineNumberReader public class BufferedReader extends Reader Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of
docs.oracle.com
Scanner를 BufferedReader로 바꾸고 실행했는데 Null Pointer 런타임에러가 나왔다.
다음은 Null Pointer Exception에 대한 설명이다.
Thrown when an application attempts to use null in a case where an object is required. These include:
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null object. NullPointerException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.
정확히는 이해하지 못했지만, null이 만들어지게 하면 안되는 것 같다.
이전까지는 문자열 비교를 할 때
String.equals("Hello");
이렇게 작성했는데 이렇게 작성하게 되면 throw된다. String이 기본자료형이 아니고 객체이기 때문인 것 같다.
문자열을 비교할때 NullPointerException이 발생하지 않게 하려면
"Hello".equals(String);
이런식으로 비교하려는 문자열을 먼저 배치해줘야 한다.
이 오류까지 고치고 나니 통과가 됐다!
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String command;
int[] stack = new int[n+1];
int top=0;
for(int i = 0; i<n; i++) {
command = br.readLine();
String[] com = command.split(" "); //split()만 입력해도 된다.
if("push".equals(com[0])) {
stack[++top] = Integer.parseInt(com[1]); String형태로 받은 숫자를 정수형으로 바꾼다.
}
else if("pop".equals(com[0])) {
if(top==0) System.out.println("-1");
else if(top>=1) System.out.println(stack[top--]);
}
else if("size".equals(com[0])) {
System.out.println(top);
}
else if("empty".equals(com[0])){
if(top==0) System.out.println("1");
else System.out.println("0");
}
else if("top".equals(com[0])) {
if(top==0) System.out.println("-1");
else System.out.println(stack[top]);
}
}
br.close();
}
catch(IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
풀고나니 공부할 것이 많아졌다.
StringBuilder, StringTokenizer, bufferWriter와 try-catch, exception.
공부할게 많고많다!
'Algorithm' 카테고리의 다른 글
[정렬] Quick Sort (0) | 2022.03.25 |
---|---|
[BOJ][python] 수 정렬하기 3 - 10989 (0) | 2022.03.21 |
[재귀함수]하노이탑 (0) | 2021.12.12 |
[자료구조] 그래프와 트리 (0) | 2021.11.05 |
[python][programmers] 정렬 - k번째수 (0) | 2021.10.05 |