본문 바로가기
코딩테스트

x 사이의 개수 개선하기

by 어떻게말이름이히힝 2025. 3. 25.

코딩테스트 연습 - x 사이의 개수 | 프로그래머스 스쿨

 

처음 만든 코드

class Solution {
    public int[] solution(String myString) {
        List<Integer> answer = new ArrayList<>();
        String[] mString = myString.split("");
        int cnt = 0;
        for(String s : mString) {
            if(s.equals("x")) {
                answer.add(cnt);
                cnt = 0;
                continue;
            }
            cnt++;
        }
        answer.add(cnt);
        return answer.stream().mapToInt(i -> i).toArray();
    }
}

 

결과

 

문제

1. 문자열을 한 글자씩 분리하는 split("") -> myString의 길이만큼 문자열 배열이 생성되서 메모리 사용량이 증가하고 성능이 저하됨

2. List<Integer>를 int[]로 변환하는 과정에서 stream().mapToInt()를 사용
   : List<Integer>의 요소를 스트림으로 변환, 각 요소를 int로 변환(언박싱), 새로운 int[] 배열을 생성하고 값을 복사하는 과정을 거침

 

변환 과정에서 많은 시간이 소요되는 것으로 생각됨. 

해당 변환 과정이 필요없도록 개선 방향을 잡음

 

코드 개선

 

class Solution {
    public int[] solution(String myString) {
        int i = 0;
        String[] mString = myString.split("x");
        int[] answer;
        
        if(myString.endsWith("x")){
            answer = new int[mString.length+1];
        } else {
            answer = new int[mString.length];
        }
        
        for(String s : mString) {
            answer[i] = s.length();
            i++;
        }
        
        return answer;
    }
}

 

결과