문제 보기
문제 분석
[요약]
주어진 케이스 별로 1)첫 번째 줄 : 녹음기에 담긴 모든 울음소리, 2)두 번째 줄~'What does the fox say'이전 까지의 줄 : 각 동물의 울음소리 이다. 1번 문장을 2번에서 언급한 동물의 울음소리를 제외하여 출력한다.
[푸는 과정]
각 동물의 울음소리를 " goes "로 잘라내서 HashTable에 담고 차례대로 'replace()'를 써서 해당 울음소리를 모두 ''로 바꾼 뒤 출력하는 방법이 바로 떠올랐다. 그런데 여기서 문제 발생. 예제의 'seal'은 'ow'소리를 내며 울고 모든 동물 울음소리를 담은 문장에 'pow'가 포함되어 있다. 그래서 만약 'replace("ow", "");'를 쓴다면 'pow'라는 단어가 'p'로 변해버린다.
그래서 다른 방법을 생각했다. 온전하게 한 단어씩 비교 하려면 split(" ")를 사용해 한 단어씩 배열에 담아 주고 배열의 값을 확인하며 단어를 제거해주는 방법을 썼다.
더 자세한 설명은 하단의 코드와 함께 올려 놓았다.
코드 보기
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
for(int k=0; k<N; k++){
//모든 울음소리 문장(녹음 된 문장)
String fullRecorded = br.readLine();
//동물의 종류별 울음소리
Set<String> soundSet = new HashSet<>();
String animal = "";
//'what does the fox say?'라는 문장이 나올때까지 읽어들인다.
while(!(animal = br.readLine()).equals("what does the fox say?")){
String[] strArray = animal.split(" goes ");
soundSet.add(strArray[1]);
}
//모든 울음소리 문장을 단어별로 배열에 담는다.
String[] words = fullRecorded.split(" ");
String result = "";
for(int i=0; i<words.length; i++){
//HashSet(동물 종류별 울음소리)에 없는 단어라면 문장에 더해준다.
if(!soundSet.contains(words[i])){
result += words[i] + " ";
}
}
//맨 뒤의 공백을 제거하고 출력한다.
System.out.println(result.substring(0, result.length()-1));
}
}
}
변수를 설명하자면 | 녹음 된 문장 : fullRecorded → 단어로 분리 : words[] | 동물별 울음소리 : soundSet | 이다. 처음에 HashTable로 Map을 쓸까 했는데 사실 답을 구하는데는 울음소리만 있으면 되기 때문에 그냥 Set을 사용했다. 그리고 Set의 메소드인 'contains()'를 사용하면 문제해결 끝.
다른 풀이(원래 작성했던 코드)
package parsing;
import java.io.*;
import java.util.*;
public class Parsing9536 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
for(int k=0; k<N; k++){
List<String> soundList = new ArrayList<>();
String fullRecorded = br.readLine();
String animal = "";
while(!(animal = br.readLine()).equals("what does the fox say?")){
String[] strArray = animal.split(" goes ");
soundList.add(strArray[1]);
}
String[] words = fullRecorded.split(" ");
for(int i=0; i< soundList.size(); i++){
String target = soundList.get(i);
for(int j=0; j< words.length; j++){
if(words[j].equals(target)){
words[j] = "";
}
}
}
String result = "";
for(int i=0; i< words.length; i++){
if(!words[i].equals("")){
result += words[i] + " ";
}
}
result = result.substring(0, result.length()-1);
System.out.println(result);
}
}
}
이건 앞의 코드에서 사용했던 'Set'의 'contains()'메소드가 떠오르기 전 작성했던 코드이다. Set대신에 배열을 사용하여 비교해주었다. 확실히 Set을 사용하니 코드의 길이가 짧아졌다.(만족)
'개발 As 공부 > Algorithm' 카테고리의 다른 글
[백준] 8595번: 히든 넘버 - JAVA (0) | 2022.04.07 |
---|---|
[백준] 11497번: 통나무 건너뛰기 - JAVA (0) | 2022.03.25 |
[프로그래머스] 주차 요금 계산 - JAVA (0) | 2022.03.24 |
[알고리즘] 동적 프로그래밍, DP(Dynamic Programming) (0) | 2022.02.18 |
[알고리즘] 이진탐색 (0) | 2022.02.15 |