inblog logo
|
ricota-cheeze
    TILcoding-test

    99클럽 코테 스터디 30일차 TIL (비기너)

    List - capacity와 size의 차이를 이해하자
    jeenie's avatar
    jeenie
    Jun 17, 2024
    99클럽 코테 스터디 30일차 TIL (비기너)

    https://leetcode.com/problems/shuffle-string/

    <문제>

    You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. Return the shuffled string.

    <문제해설>

    문자열 s, 숫자배열 indices가 주어진다.
    indices에 주어진 index에 맞게 s를 재배열하라.

    <풀이>

    class Solution {
        public String restoreString(String s, int[] indices) {
            // 배열 or list?
            // map??
            char[] arr = new char[s.length()];
            // List list = new ArrayList();
    
            for (int i = 0; i < indices.length; i++) {
                int num = indices[i];//4
                arr[num] = s.charAt(i);
                // list.set(num, s.charAt(i));
            }
    
            String answer = "";
    
            for(char c : arr){
                answer += c;
            }
    
            return answer;
    
            // return Arrays.toString(arr); //"[l, e, e, t, c, o, d, e]"...
    
            // return String.join(",",list);
    
        }
    }

    <접근방식>

    1. 어떤 식으로 접근해야 할까?

    처음에는 key-value를 구조의 map을 고려했었다. ‘key에는 인덱스를, value에는 문자를 넣고 key를 기준으로 오름차순 정렬하면 되지 않을까?’
    그런데 map 사용에 익숙하지 않아서 빠른 포기..

    ⭐️ 임의의 자료구조를 만들고 indices에 있는 인덱스 순서대로 문자열을 넣어주면 되겠다는 생각이 들었다.

    ex) indices[0] = 4, 자료구조[4] = 문자열0번째값

    indices[i] = n, 자료구조[n] = 문자열i번째값

    1. 어떤 자료구조를 사용해야 할까? (feat. List를 사용하려다가 포기한 이유)

    List list = new ArrayList();
    list.set(num, s.charAt(i)); // IndexOutOfBoundsException

    IndexOutOfBoundsException 발생!
    List는 배열과 달리 어떤 인덱스든 자유롭게 접근 가능한 거 아니었나?? 😤

    👉 list는 empty고 size()=0이야. n번째 인덱스에 접근(데이터를 넣거나, 가져오거나)하려면 n번째까지 데이터를 가지고 있어야 해!

    배열(array) : 선언 시 n개의 공간 확보 → capacity (용량) (데이터 용량 변경 불가능)
    n개의 범위 내에서 원하는 인덱스에 자유롭게 접근 가능 → size

    리스트(list) : 선언 시 10개의 공간 확보 → capacity (용량) (데이터 용량 변경 가능)

    0부터 데이터가 존재하는 인덱스까지 접근 가능 (데이터가 없는 구간을 건너뛰어서 접근할 수 없다) → size

    /*
            public void add(int index, E element) {
                rangeCheckForAdd(index);
                //~~
            }
    */
    
    //실제로 index가 사이즈보다 크면 예외가 발생한다
    private void rangeCheckForAdd(int index) {
            if (index > size || index < 0)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

    test.set(5, "test"); is the statement that throws this exception, since your ArrayList is empty (size() would return 0 if you got to that statement), and you can't set the i'th element if it doesn't already contain a value. You must add at least 6 elements to your ArrayList in order for test.set(5, "test"); to be valid.

    new ArrayList(10) doesn't create an ArrayList whose size is 10. It creates an empty ArrayList whose initial capacity is 10.

    https://stackoverflow.com/questions/34526362/set-method-of-arraylist-throwing-indexoutofboundsexception

    <다른 코드 참고>

    class Solution {
        public String restoreString(String s, int[] indices) {
            int n = indices.length;
            char[] result = new char[n];
            
            for (int i = 0; i < n; i++) {
                result[indices[i]] = s.charAt(i);
            }
            
            return new String(result); //!!
        }
    }

    char[] 배열로 바로 String을 만들어주는 생성자가 있었구나!

    <마무리하며>

    ☁️ 자료구조←>문자열 변환은 언제쯤 능숙하게 할 수 있는걸까? split, join 같은 메소드들이 아직 생소하다..!
    size, length도 사용할 때마다 헷갈린다.

    🌥️ 자료구조 개념이 부족한 것 같아서 ‘김영한 강사님 -자바 중급2’를 시작했다. 자료구조 마스터가 될거야!

    #99클럽 #코딩테스트 준비 #개발자 취업 #항해99 #TIL

    Share article

    ricota-cheeze

    RSS·Powered by Inblog