[프로그래머스/181902] 문자 개수 세기

☑️ 문제

프로그래머스 181902

☑️ 풀이

첫 번째 풀이

  • 문자열 각 자리 문자의 ASCII 코드를 활용하기 위해 몇 번의 코드인지 알아야 하는 줄 알고 A~Z, a~z 범위의 코드를 검색해서 풀었다..
//시간: 0.12ms
//메모리: 82.6MB

import java.util.*;

class Solution {
    public int[] solution(String my_string) {
        int[] answer = new int[52];
        Arrays.fill(answer, 0);
        
        // A ~ Z : 65 ~ 90 (answer 인덱스 : 0 ~ 25)
        // a ~ z : 97 ~ 122 (answer 인덱스 : 26 ~ 51)
        for (int i = 0; i < my_string.length(); i++) {
            int num = my_string.charAt(i);
            if (num >= 65 && num <= 90) {
                answer[num - 65]++;
            } else {
                answer[num - 71]++;
            }
        }
        return answer;
    }
}
  • 다른 사람들의 풀이를 보고 char 타입의 문자를 비교 연산자(>=, <)로 비교하면 내부적으로 ASCII 코드 비교가 되는 것을 알았다.

두 번째 풀이

  • 첫 번째 풀이를 개선하여 문자 비교 연산을 활용했다.
  • 대문자와 소문자를 구분하여 알파벳의 순서를 직접 계산한다.
//시간: 0.11ms
//메모리: 82.4MB

import java.util.*;

class Solution {
    public int[] solution(String my_string) {
        int[] answer = new int[52];
        Arrays.fill(answer, 0);

        for (int i = 0; i < my_string.length(); i++) {
            char c = my_string.charAt(i);
            if (c >= 'a') {
                answer[(c - 'a' + 26)]++;
            } else if (c >= 'A') {
                answer[(c - 'A')]++;
            }
        }
        return answer;
    }
}

© 2021. All rights reserved.

yaejinkong의 블로그