중복단어제거

bkboy·2022년 5월 17일
0
post-thumbnail

문제

N개의 문자열이 입력되면 중복된 문자열은 제거하고 출력하는 프로그램을 작성하세요.
출력하는 문자열은 원래의 입력순서를 유지합니다.

제한사항

입출력 예

풀이

function solution(s) {
  let answer = [];
  for (let x of s) {
    if (answer.includes(x)) {
      continue;
    } else {
      answer.push(x);
    }
  }

  return answer.join('\n');
}
let str = ['good', 'time', 'good', 'time', 'student'];
console.log(solution(str));
  • includes를 이용해 이미 포함되어있는지 확인해서 그러면 continue해준다.
  • 이래도 되고 set을 또 이용해도 된다.
function solution(s) {
  let answer = new Set();
  for (let x of s) {
    answer.add(x);
  }

  return [...answer].join('\n');
}
let str = ['good', 'time', 'good', 'time', 'student'];
console.log(solution(str));
  • 그냥 넣기만 하면 돼서 더 간단해보인다.
  • 일부러 add를 썼다.
const sol = (str) => {
  const answer = new Set(str);
  return answer;
};
let str = ["good", "time", "good", "time", "student"];
console.log(sol(str));

사실 add도 안 써도 된다.

profile
음악하는 개발자

0개의 댓글