회고록 블로그

[LeetCode 코테 풀기] 205. Isomorphic Strings 본문

4. 기타 공부/코테 준비

[LeetCode 코테 풀기] 205. Isomorphic Strings

김간장 2022. 7. 18. 20:29

목표 : 1일 1문제 풀기

 

사용 언어 : JavaScript

문제 : Day2. String

https://leetcode.com/problems/isomorphic-strings/

 

Isomorphic Strings - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

isomorphic?

https://ko.wikipedia.org/wiki/%EB%8F%99%ED%98%95_%EC%82%AC%EC%83%81

문제를 대충 해석해보니, s의 문자(charater)가 t와 매핑된다는 것 같다.

 

 

내 풀이 :

머리 굴리느라 진짜 힘들었다... 더러운 코드이지만 포기하지 않고 풀었다는 건 뿌듯하다.

 

결과

const isIsomorphic = function(s, t) {
    const array = [[], []];

    return (s.split("").every((currentValue, index) => {
        const findIndex = array[0].indexOf(currentValue);
        if (findIndex === -1) {
            array[0].push(currentValue);
            array[1].push(t[index]);
        } else {
            if (array[1][findIndex] !== t[index])
                return false;
        }
        if (array[1].filter(element => element === t[index]).length > 1) {
            return false;
        }
        return true;
    }));
};

 

1.

2차원 배열을 하나 만든 후 시작했다.

문자열 s와 t를 한 글자씩 배열에 넣은 다음, false의 조건에 해당하는지 확인한다.

즉, 

array[0]에는 문자열 s를 점검하고 값을 넣을 것이고 array[1]에는 문자열 t를 점검하고 값을 넣었다.

 

 

2.

String.prototype.split 메서드 : 문자열 s를 구분자 기준으로 나눠서 배열로 만든다.

구분자로 빈문자열("")을 줘서 한 글자씩 떼었다.

근데 만들고 나서 알았는데 구분자를 빈 문자열("")로 주면 아스키코드 문자 기준으로 하나씩 나누는게 아니라 UTF-16 코드유닛 기준으로 나눈다고 한다. 그래서 써로게이트 페어가 망가질 수 있다고 한다.

즉, "😃😎🎃happy"와 같은 문자열이 있다면 ["�", "�", "�", "�", "�", "�", "h", "a", "p", "p", "y"]로 나뉜다.

 

그래서 깨짐 없이 나누고 싶다면 다음과 같은 방법을 사용해야한다고 한다.

해결방법 : https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402

 

How to get character array from a string?

How do you convert a string to a character array in JavaScript? I'm thinking getting a string like "Hello world!" to the array ['H','e','l','l','o',' ','w','o','r','l','d','!']

stackoverflow.com

 

문제에서 s와 t는 유효한 아스키 문자로 구성되어 있다고 했으니, split이 아니라 스프레드 구문을 쓰는게 더 적절했을 것이다.

(이유 : 확장된 아스키코드 고려)

  • s and t consist of any valid ascii character.

 

3. 

Array.prototype.every : 배열 안의 모든 요소를 돌면서 인자로 주어진 판별 함수를 통과하는지 테스트한다.

false를 반환할 때까지 배열의 각 요소를 돈다. 모든 값이 참이면 true가 반환된다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/every

 

 

4.

Array.prototype.indexOf : 배열에서 지정된 요소를 찾아서 가장 첫번째로 만나는 인덱스를 반환하고, 존재하지 않으면 -1을 반환한다.

  • String에도 있다.

 

every 메서드를 사용한 이유는, 문자열 s를 한 글자(char)씩 떼어서 돌기 위해서이다.

문자열 s에서 떼어낸 각각의 문자(char)가 array라는 2차원 배열에 존재하는지 확인하기 위한 용도로 indexOf 메서드를 사용했다.

 

문자열 s가 "paper"이고, 문자열 t가 "title"이라고 하면

p, a, p, e, r을 돌면서 array[0] 배열에 저장되어 있는지 보는 것이다.

만약 없으면 array[0]에 "p"를 푸쉬하고 array[1]에는 그에 상응하는 문자열 t의 문자, "t"를 푸쉬한다.

만약 있다면 해당 문자가 있는 인덱스를 가지고 와서, array[1]의 문자와 동일한지 체크했다.

 

마지막으로 array[1]의 중복을 확인해서 중복되는 값이 있으면 false를 반환시켰다.

=> No two characters may map to the same character, ...(생략)... 라고 문제에서 주어졌기 때문이다.

 

 

5. 

Array.prototype.filter : 주어진 함수를 통과하는 모든 요소를 모아 새로운 배열을 만들어서 반환한다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

 

 

 

 

풀어낸 것보다 베스트 답안이 무엇인지 찾아보고 공부하는게 더 중요한 것 같다.

가장 많은 투표를 받은 베스트 답안 :

 

1) 

https://leetcode.com/problems/isomorphic-strings/discuss/58020/Javascript-6-lines-solution

 

Javascript 6 lines solution - LeetCode Discuss

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

obj 객체를 이용한 방법인 것 같은데

만약 문자열 s가 "paper"이고 문자열 t가 "title"이라고 한다면 다음과 같이 만들어질 것 같다.

// string s : paper
// string t : title

obj = {
    'sp': 't',
    'tt': 'p',
    'sa': 'i',
    'ti': 'a',
    'se': 'l',
    'tl': 'e',
    'sr': 'e',
    'te': 'r'
}

오늘도 한 수 배워갑니다.

 

 

 

2)

https://leetcode.com/problems/isomorphic-strings/discuss/345129/JS-hashmap-solution

 

JS hashmap solution - LeetCode Discuss

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

Map과 Set을 이용한 방법인 것 같은데, 맵과 셋을 아직 제대로 이해하지 못해서 스킵하기로 했다.

하지만 곧 돌아와서 코드를 찬찬히 이해해볼 예정임..

Comments