[백준]1157 단어 공부

차누·2023년 6월 5일
0

백준 1157번 문제 코드 해석 및 정리

문제

알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.


처음코드 작성

입력값을 대문자와 소문자를 구분하여 A ~ Z, a ~ z까지 각각의 인덱스 값을 찾아 더하여 최댓값을 구하는 코드를 작성했다. 하지만 문제를 읽어보니 "대문자와 소문자는 구분하지 않는다"라는 문장을 보고
for 문에서 대문자와 소문자를 분리해서 위치값을 찾는 것은 비효율적인 코드라고 느껴 다시 작성하였다.

		for(int i =0 ; i < str.length(); i++) {
			
            //입력값 문자 하나하나씩 돌아 대문자 A ~ Z까지 범위안에 있을때 그 인덱스를 ++해준다
            
			if('A' <= str.charAt(i) && str.charAt(i) <= 'Z') {
				arr_int[str.charAt(i) -'A']++; 
			}
			
             //입력값 문자 하나하나씩 돌아 소문자  a ~ z까지 범위안에 있을때 그 인덱스를
             ++해준다.
			else {
				arr_int[str.charAt(i) - 'a']++;
			}
		}

첫 번째 전체 코드


//if문써서 비교
//1157 단어공부

import java.util.Scanner;

public class code_test{
	public static void main(String [] args) {
		Scanner sc = new Scanner(System.in);
		int [] arr_int = new int[26];
		String str = sc.nextLine();
		
		for(int i =0 ; i < str.length(); i++) {
			
			if('A' <= str.charAt(i) && str.charAt(i) <= 'Z') {
				arr_int[str.charAt(i) -'A']++; //해당 인덱스값 증가
			}
			
			else {
				arr_int[str.charAt(i) - 'a']++;
			}
		}
		
		int max = 0;
		
		char ch = ' ';
		
		for(int i =0; i < 26; i++) {
			
			//가장많은 문자열 찾기
			if(arr_int[i] > max) {
				max = arr_int[i];
				//해당 인덱스에 대응하는 문자로 변환
				ch = (char )(i +65);
			}
			
			//만약에 같은 최대값이 2개가 있을경우 ?으로 치환
			else if(arr_int[i] == max) {
				ch = '?';
			}
			
			
			
		}
		
		System.out.print(ch);
		
	}
}

두 번째 전체 코드

import java.util.Scanner;

public class B1157 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
        
        // 모든 문자 대문자로 바꿔주기
		String str = sc.nextLine().toUpperCase(); 
		sc.close();

		int[] arr = new int[26]; // 알파벳 배열 선언
		int max = 0; 
		char result = ' ';

		// 사용된 알파벳의 배열에 1씩 증가시킨다.
		for (int i = 0; i < str.length(); i++) {
			arr[str.charAt(i) - 65]++; // 65는 'A'

			// 최대값 구하기
			if (max < arr[str.charAt(i) - 65]) {
				max = arr[str.charAt(i) - 65];
				result = str.charAt(i);

				// 최대값이 중복이라면 ? 출력
			} else if (max == arr[str.charAt(i) - 65]) {
				result = '?';
			}
		}
		System.out.println(result);
	}

}

출력값을 대문자로 해야 되기 때문에 입력값을 대문자로 변환했고, 전 코드 보다 간결해지고 이해하기 쉬웠다.

profile
to be good programmer

0개의 댓글