https://www.acmicpc.net/problem/1213
1213번: 팰린드롬 만들기
첫째 줄에 문제의 정답을 출력한다. 만약 불가능할 때는 "I'm Sorry Hansoo"를 출력한다. 정답이 여러 개일 경우에는 사전순으로 앞서는 것을 출력한다.
www.acmicpc.net
저는 구현을 통해 문제를 해결하였습니다.
먼저 각 알파벳의 개수를 구하였고, 홀수 개수가 여러개라면 바로 불가능한 문자를 리턴하고, 아니라면 홀수 개수의 알파벳만 남겨두고 나머지는 두개의 StringBuilder에 각각 하나씩 넣고 마지막에 홀수 개수의 알파벳을 하나의 StringBuilder에 넣고 다른 하나는 뒤집어서 합쳐주어 문제를 해결하였습니다.
package BOJ.etc;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BOJ_1213 {
private static final int SIZE = 26;
private static final String FAIL = "I'm Sorry Hansoo";
private static final char EMPTY = '5';
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String command = br.readLine();
int[] cnt = new int[SIZE];
int totalCnt = 0;
for(int i = 0 ; i < command.length() ; i++){
char ch = command.charAt(i);
cnt[ch - 'A']++;
totalCnt++;
}
String result = cal(command,cnt,totalCnt);
System.out.println(result);
}
private static String cal(String command, int[] cnt, int totalCnt) {
StringBuilder front = new StringBuilder();
StringBuilder back = new StringBuilder();
char temp = EMPTY;
boolean haveOdd = false;
for(int i = 0 ; i < SIZE ; i ++){
if(haveOdd && cnt[i] % 2 != 0){
return FAIL;
}
if(cnt[i] % 2 != 0){
haveOdd = true;
}
}
for(int i = 0 ; i < SIZE ; i ++){
while(cnt[i] >= 2){
front.append((char)('A'+i));
back.append((char)('A'+i));
cnt[i] -= 2;
totalCnt -= 2;
}
if(cnt[i] == 1){
temp = (char)('A' + i);
}
}
if(temp != EMPTY){
front.append(temp);
}
String result = front.toString() + back.reverse().toString();
return result;
}
}
'알고리즘' 카테고리의 다른 글
백준 14218번 그래프 탐색2 (JAVA) (0) | 2023.09.18 |
---|---|
백준 1812번 사탕 (JAVA) (0) | 2023.09.17 |
백준 23029번 시식 코너는 나의 것(JAVA) (0) | 2023.09.15 |
백준 1057번 토너먼트 (JAVA) (0) | 2023.09.14 |
백준 1080번 행렬 (JAVA) (0) | 2023.09.13 |