알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.
입력
첫째 줄에 알파벳 대소문자로 이루어진 단어가 주어진다. 주어지는 단어의 길이는 1,000,000을 넘지 않는다.
출력
첫째 줄에 이 단어에서 가장 많이 사용된 알파벳을 대문자로 출력한다. 단, 가장 많이 사용된 알파벳이 여러 개 존재하는 경우에는 ?를 출력한다.
예제 입력
Mississipi
예제 출력
?
예제 입력2
zZa
예제 출력2
Z
예제 입력3
baaa
예제 출력3
A
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
s = s.toUpperCase();
int arr[] = new int[26];
int max = 0, index = 0;
for(int i=0; i<s.length(); i++){
int tmp = s.charAt(i);
arr[tmp-65]++;
}
for(int i=0; i<arr.length; i++){
if(max < arr[i]){
max = arr[i];
index = i+65;
}
else if(max == arr[i]){
index = '?';
}
}
System.out.println((char)index);
}
}
일단 대소문자로 받아서 출력을 대문자로 하기 때문에 일단은 입력받은 string s 값을 s.toUpperCase()함수를 이용해서 전체를 대문자로 변경
알파벳의 숫자를 세야하기 때문에 int형의 26크기를 가진 배열을 생성
문자열 크기만큼 for문을 돌면서 string의 값 하나하나짤라서 순서대로 넣어줘야하는데
-> 이부분은 아스키코드를 사용했다. 대문자 A의 시작이 65이기 때문에 만약에 A가 들어왔을때 그 문자에서 65를 빼주면 0이 될 것이고 B은 66일 것이며 65를 빼주면 1이 될것이다. 이렇게 순서대로 진행되기 때문에 배열에 arr[문자-65]++ 이렇게 처리해주면 순서대로 갯수가 있는대로 추가하기 쉽다
이렇게 알파벳의 카운팅이 끝나고 나면, 최대값을 찾아야한다.
max라는 변수를 두어서 카운팅해둔 배열을 돌면서 만약 max값(0으로 초기화해둠)보다 크면 max값으로 변경해주고, 해당 대문자를 찾아야하기 때문에 처음에 65를 빼면서 계산했던것과 반대로 65를 더해주면 그 대문자로 변경된다.
만약 max와 숫자가 같다면 ?를 출력하도록 처리해주고
for문이 끝나고나서 char형으로 형변환하면서 출력하면 끝!
2번째시도
쉽네쉽네하면서 풀었는데 시간초과..?!
예제는 다 통과했는데 왜그럴까 보면 포문이 2개여서그런가보다.. 사실 문제 풀면서 이상한 변수들도 많이 만든거 같으니까 새로운방법으로 풀어보자..
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String tmp = sc.next().toUpperCase();
int[] arr = new int[tmp.length()];
int max = 0;
for(int i=0; i<arr.length; i++){
int cnt=0;
for(int j=0; j<tmp.length(); j++){
if(tmp.charAt(j) == tmp.charAt(i) && j!=i){
cnt++;
}
}
arr[i] = cnt;
if(arr[i] > max)
max = arr[i];
}
ArrayList<Character> arrayList = new ArrayList<Character>();
for(int i=0; i<arr.length; i++){
if(arr[i] == max){
arrayList.add(tmp.charAt(i));
}
}
boolean logic = true;
for(int i=0; i<arrayList.size()-1; i++){
if(arrayList.get(i) != arrayList.get(i+1))
logic = false;
}
if(logic)
System.out.println(arrayList.get(0));
else
System.out.println("?");
}
}
결국 방법을 찾기 힘들어서 문제의 질문페이지를 슬쩍봤는데 알파벳 배열로 두라는 힌트를 통해서 아스키코드를 활용하는것 까지 이어져서 문제를 풀 수 있었다! 결과적으로는 처음에 풀었던 것과 똑같다 저번에도 힌트보고 풀었나..
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String tmp = sc.next().toUpperCase();
int[] alpha = new int[26];
for(int i=0; i<tmp.length(); i++){
alpha[tmp.charAt(i)-65]++;
}
int max = 0;
int result = 0;
for (int i=0; i<alpha.length; i++) {
if (alpha[i] > max){
max = alpha[i];
result = i+65;
}else if(alpha[i] == max){
result = '?';
}
}
System.out.println((char)result);
}
}