본문 바로가기

JAVA

BAEKJOON(백준) 문자열 - 1157번 JAVA CODE

package BaekJoon;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
	
	public static void main(String[] args) throws IOException {
    
    	//BufferedReader 선언
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		Boolean bt = false;

		//문자열 입력 받기
		String str = br.readLine();
        
        
		char[] charac = null;
        //문자열 길이 추출
		int len = str.length();
		int[] count = new int[len];
		
		//문자열 전부 대문자로 변환
		str = str.toUpperCase();
        //문자열 문자로 쪼개주기
		charac = str.toCharArray();
		
		for(int i=0; i<len; i++) {
			for(int j=i+1; j<len; j++) {
            	//문자 하나씩 비교해서 같으면 각 단어 위치의 인덱스 번호 count 증가
				if(charac[i] == charac[j])
					count[i]++;
			}
		}
		
		int max = -1;
		int max_i = 0;
		
        //가장 많이 입력된 문자 찾기
		for(int i=0; i<len; i++) {
			if(count[i] > max) {
				max = count[i];
				max_i = i;
			}
		}
		
        //단어의 수가 같을 여러 개 일때 bt를 true로 변환
		for(int i=0; i<len; i++) {
			if(i != max_i)
				if(count[i] == count[max_i])
					bt = true;
		}
		
        //단어의 수가 같을 때는 '?'출력
		if (bt == true)
			System.out.println("?");
        //아닐 때는 단어 그대로 출력
		else
			System.out.println(charac[max_i]);
	}
}