저장을 습관화

프로그래머스 LV.0 중복된 문자 제거 본문

코딩 테스트/프로그래머스 - 자바스크립트

프로그래머스 LV.0 중복된 문자 제거

ctrs 2023. 9. 22. 00:15

프로그래머스 LV.0 중복된 문자 제거

https://school.programmers.co.kr/learn/courses/30/lessons/120888

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

1. 문제 명

중복된 문자 제거


2. 문제 설명

문자열 my_string이 매개변수로 주어집니다. my_string에서 중복된 문자를 제거하고 하나의 문자만 남긴 문자열을 return하도록 solution 함수를 완성해주세요.


3. 제한 사항

- 1 ≤ my_string ≤ 110

- my_string은 대문자, 소문자, 공백으로 구성되어 있습니다.

- 대문자와 소문자를 구분합니다.

- 공백(" ")도 하나의 문자로 구분합니다.

- 중복된 문자 중 가장 앞에 있는 문자를 남깁니다.


4. 예시

my_string result
"people" "peol"
"We are the world" "We arthwold"


5. 기본 제공 코드

function solution(my_string) {
    var answer = '';
    return answer;
}


6. 제출한 내 답

//

 

6-2. VSC에 작성한 내용

const solution = (my_string) => {
  // 1번 방법 - Set
  // return [...new Set(my_string)].join("");
  //
  // 2번 방법 - Set 두번째
  // return Array.from(new Set([...my_string])).join("");
  //
  // 3번 방법 - filter와 indexOf
  // return my_string
  //   .split("")
  //   .filter((v, i, arr) => {
  //     return arr.indexOf(v) === i;
  //   })
  //   .join("");
  //
  // 4번 방법 - reduce와 includes
  // return my_string.split("").reduce((acc, cur) => {
  //   return acc.includes(cur) ? acc : acc + cur;
  // }, "");
  //
  // 5번 방법 - forEach
  // let answer = [];
  // my_string.split("").forEach((element) => {
  //   if (!answer.includes(element)) {
  //     answer.push(element);
  //   }
  // });
  // return answer.join("");
  //
  // 6번 방법 - for of
  let answer = "";
  for (const char of my_string) {
    if (!answer.includes(char)) {
      answer += char;
    }
  }
  return answer;
};

// 테스트
console.log(solution("people"));
console.log(solution("We are the world"));


7. 특이사항

아래와 같이 풀려고 씹고 뜯고 하다가

const solution = (my_string) => {
  my_string = my_string.split("");

  for (i = 0; i < my_string.length; i++) {
    if (my_string.slice(i + 1).indexOf(my_string[i]) !== -1) {
      console.log(my_string.slice(i + 1).indexOf(my_string[i]));
      // let idx = my_string(i + 1).indexOf(my_string[i]);
      // my_string.splice(idx, 1);
    }
  }

  return my_string;
};

// 테스트
console.log(solution("people"));
console.log(solution("We are the world"));

도저히 못풀겠는데 정답율을 86%고 풀어낸 사람인 13,400명이고

뭐지 나만 모르는 뭔가가 있는건가.. 싶어서 검색했다..

 

아예 문자열과 배열에서 중복된 값을 하나만 남기고 모두 지우는 방법이 여러가지 있더라

그랬다

나만 모르고 남들 다 알고 있었다..

 

공부 열심히 해야지..

 

[참조]

https://ctrs.tistory.com/340

 

자바스크립트 문자열과 배열에서 중복값 제거 Set, filter, indexOf, reduce, includes, forEach, for of

[내용 출처] https://blacklobster.tistory.com/14 간단간단! 자바스크립트(JS) 문자열, 배열 중복값 제거하기 이전 글에서는 자바스크립트(JavaScript)의 문자열과 배열의 중복값 찾기를 알아보았는데요. 이번

ctrs.tistory.com

 

공부하고 다시 보니 내가 이미 알고 있던 내용이 대부분이었다..

forEach나 includes에 대해서 조금만 더 깊게 생각해봤으면 스스로 풀 수 있었을텐데 너무 아쉽다.

 


8. 다른 사람이 작성한 답

8-1. 가장 많이 쓰인 풀이법 Set

function solution(my_string) {
    return [...new Set(my_string)].join('');
}

 

8-2. filter와 indexOf

var solution=s=>[...s].filter((c,i)=>s.indexOf(c)==i).join('')

 

8-3. for of

function solution(my_string) {
    const arr = my_string.split('')
    const set = new Set()
    for (const i of arr) {
        set.add(i)
    }
    return [...set].join('')
}