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

list 데이터 입출력 기준은 size!
jeenie's avatar
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번째까지 데이터를 가지고 있어야 해.”

개인적으로 이 개념이 이해가 될랑말랑 하면서도 신기한 것 같다. (선언하면 n개의 공간을 확보해주는 배열과 달리) list를 선언하면 사이즈는 0이고, 공간을 확보해주지 않는다 (empty). capacity와 size는 다른 거구나. 리스트에 접근하려면 size를 기준으로 접근해야 하는구나.
size=실제 데이터 갯수, capacity=list의 용량!!

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
RSSPowered by inblog