티스토리 뷰
더 깔끔한 노션을 원한다면
Baekjoon 9935 문자열 폭발 - 메모리 초과
String 메모리 초과 때문에 마음 고생을 하게 했던 문제.
www.notion.so
9935번: 문자열 폭발
첫째 줄에 문자열이 주어진다. 문자열의 길이는 1보다 크거나 같고, 1,000,000보다 작거나 같다. 둘째 줄에 폭발 문자열이 주어진다. 길이는 1보다 크거나 같고, 36보다 작거나 같다. 두 문자열은 모�
www.acmicpc.net
String 메모리 초과 때문에 마음 고생을 하게 했던 문제.
처음 생각 - contains, replace
문제 보고 바로 떠오른건 contains, replace였다.
private static void P9935() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String answer = "";
String string = br.readLine();
String boomString = br.readLine();
while(string.contains(boomString)) {
string = string.replaceAll(boomString, "");
}
if(string.length() == 0){
System.out.println("FRULA");
} else {
System.out.println(string);
}
}
하지만 바로 메모리 초과!😂
힌트를 보니 스택으로 분류되어 있었다.
역시 스택❗
1. stack에 문자열(string)을 차례로 넣어준다.
for (int index = 0; index < length; index++) {
stack.push(string[index]);
if (stack.size() >= bombLength) {
if (isBomb(stack, bomb)) {
for (int b = 0; b < bombLength; b++) {
stack.pop();
}
}
}
}
2. stack의 크기가 bomb 크기와 같아지면 터질 수 있는지 검사해준다.(isBomb)
private static boolean isBomb(Stack<Character> stack, String bomb) {
for (int index = 0; index < bomb.length(); index++) {
if (stack.get(stack.size() - bomb.length() + index) != bomb.charAt(index)) {
return false;
}
}
return true;
}
메모리 초과 이유❗
String.replaceAll (regex, replacement) 접근 방식을 사용하면 한 번의 호출로 겉보기에는 교체를 수행 할 수 있지만 내부적으로 많은 추가 GC(Garbage Collection) 적격 객체가 생성된다.
따라서 문자열 교체 문제는 replace가 아닌 다른 방법을 생각하는 것이 좋다!
전체 코드
/**
* @처음생각 contains, replaceAll을 사용 => 메모리 초과(string GC)
* @포인트 스택으로 해결
*/
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Main {
public static void main(String[] args) throws java.lang.Exception {
System.out.println(P9935());
}
private static String P9935() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack<Character> stack = new Stack<>();
char[] string = br.readLine().toCharArray();
String bomb = br.readLine();
int length = string.length;
int bombLength = bomb.length();
for (int index = 0; index < length; index++) {
stack.push(string[index]);
if (stack.size() >= bombLength) {
if (isBomb(stack, bomb)) {
for (int b = 0; b < bombLength; b++) {
stack.pop();
}
}
}
}
StringBuilder sb = new StringBuilder();
for (Character ch : stack) {
sb.append(ch);
}
if (sb.length() == 0) {
return "FRULA";
} else {
return sb.toString();
}
}
private static boolean isBomb(Stack<Character> stack, String bomb) {
for (int index = 0; index < bomb.length(); index++) {
if (stack.get(stack.size() - bomb.length() + index) != bomb.charAt(index)) {
return false;
}
}
return true;
}
}
'알고리즘' 카테고리의 다른 글
Baekjoon 3111 검열 - 문자열+스택 (0) | 2020.10.04 |
---|---|
Baekjoon 2505 두 번 뒤집기 (0) | 2020.10.03 |
Baekjoon 4949 균형잡힌 세상 - 코딩 테스트 (0) | 2020.10.02 |
Baekjoon 14719 빗물 - 코딩테스트 (0) | 2020.09.27 |
Baekjoon 3687 성냥깨비 - DP (0) | 2020.09.27 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 이펙티브 자바
- Algorithm
- MSA
- Spring Boot
- AWS
- 코테
- C++
- 클린 아키텍처
- programmers
- BAEKJOON
- 디자인패턴
- 프로그래머스
- 객체지향
- Java
- kkoon9
- 이팩티브 자바
- 테라폼
- Spring
- 알고리즘
- 디자인 패턴
- kotest
- BOJ
- Kotlin
- JPA
- Effective Java
- 정규표현식
- 백준
- 클린 코드
- node.js
- Olympiad
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함