인프런 커뮤니티 질문&답변
다른 풀이방법에 대한 조언 부탁드립니다.
작성
·
181
0
import java.util.*;
import java.io.*;
class Main {
public String solution(String str) {
String answer = "";
str += "";
int[] arr = new int[26];
for(int i=0; i<str.length(); i++) { // ASCII코드와 배열을 사용해 배열에 해당 문자의 연속된 값을 넣어줌
arr[str.charAt(i)-65]++;
}
for(int i=0; i<str.length()-1; i++) {
if(str.charAt(i) == str.charAt(i+1)) {
continue;
} else if(arr[str.charAt(i)-65] == 1) { // 문자가 연속되지 않을 때
answer += str.charAt(i);
} else if(str.charAt(i+1) == '') { // 이 부분에서 else without if 오류가 남...
answer += str.charAt(i);
break;
} else {
answer += str.charAt(i) + String.valueOf(arr[str.charAt(i)-65]);
}
}
return answer;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
Main C = new Main();
System.out.println(C.solution(str));
}
}
강의를 듣기전 제가 풀어본 방법입니다. 배열에 연속된 횟수를 넣어서 구현하는 로직으로 짜봤는데, 마지막문자를 출력하는 부분에서 해결이 되지 않습니다. 이런 로직으로 짤 때 어떻게 해야 문제를 해결 할 수 있을까요?
아니면 저의 접근방법 자체가 잘못된것인지 궁금합니다.
답변 1
1
김태원
지식공유자
안녕하세요^^
아래와 같이 코드를 처리하면 됩니다만
import java.util.*;
import java.io.*;
class Main {
public String solution(String str) {
String answer = "";
int[] arr = new int[26];
for(int i=0; i<str.length(); i++) { // ASCII코드와 배열을 사용해 배열에 해당 문자의 연속된 값을 넣어줌
arr[str.charAt(i)-65]++;
}
str += " ";
for(int i=0; i<str.length()-1; i++) {
if(str.charAt(i) == str.charAt(i+1)) {
continue;
} else if(arr[str.charAt(i)-65] == 1) { // 문자가 연속되지 않을 때
answer += str.charAt(i);
} /*else if(str.charAt(i+1) == ' ') { // 이 부분에서 else without if 오류가 남...
answer += str.charAt(i);
break;
}*/else {
answer += str.charAt(i) + String.valueOf(arr[str.charAt(i)-65]);
}
}
return answer;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
Main C = new Main();
System.out.println(C.solution(str));
}
}
KKKTTTKK 가 입력되면 K3T3K2 이렇게 출력되어야 하는데 위에 코드는 이런 입력을 처리 못하는 코드입니다.





