상세 컨텐츠

본문 제목

[백준>단계별로풀어보기>문자열>단어공부(1157)]JAVA풀이

PROGRAMMING/백준알고리즘

by 니콜 키크드만 2020. 2. 11. 11:46

본문

import java.io.*;
import java.util.*;
public class Main {
	public static void main(String[] args) throws Exception{
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 입력 스트림
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); // 출력 스트림
		
		//A~Z 65~90   
		//a~z 97~122
		String []alphabatArray = br.readLine().split("");
		int []alphaCharArray = new int[alphabatArray.length];
		
		//입력 문자 > char형변환 
		for(int i = 0; i < alphabatArray.length; i++) {
			int iAlpa = (int)alphabatArray[i].charAt(0);
			if(iAlpa > 96) { // 소문자로 전부 변환
				iAlpa -= 32;
			}
			alphaCharArray[i] = iAlpa;
		}
		
		// HashMap에 알파뱃 별 갯수 구하기
		HashMap map = new HashMap<Integer, Integer>();  
		for(int i = 0; i < alphabatArray.length; i++) {
			int key = alphaCharArray[i];
			
			if(map.containsKey(key)) {
				int value = (int)map.get(key);
				map.put(key, value+1);
			}
			else {
				map.put(key, 1);
			}
		}
		
		//map객체 Int 객체로 변환 후 정렬(최대많이나온 알파뱃 구하기 위함)
		Object [] values = map.values().toArray();
		Integer[] intValues = Arrays.copyOf(values, values.length, Integer[].class);
		java.util.Arrays.sort(intValues);
		
		
		int getMaxInt = intValues[intValues.length-1]; // 가장 많이 나온 알파뱃
		if(intValues.length == 1) { //사용자가 입력을 하나만 한 경우
			bw.write( (char)(int)getKey(map, getMaxInt)); 
		}
		else {
			if(getMaxInt == intValues[intValues.length-2]) { // 가장 많이 나온 알파뱃 갯수가 2개 이상일때
				bw.write("?");
			}else {
				bw.write( (char)(int)getKey(map, getMaxInt));
			}
		}
		
		bw.flush();
		bw.close();
	}
	
	
	//map파일에서 value값에 맞는 key값 구하는 메소드
	private static Object getKey(HashMap map, int findValue) {
		for(Object o : map.keySet()) {
			if(map.get(o).equals(findValue)) {
				return o;
			}
		}
		return new Object();
	}
}

궁금한건 댓글 주세요

알고리즘에 최선의 답은 없습니다.

 

반응형

관련글 더보기

댓글 영역