CodeWars 코딩 문제 2021/02/16 -Scramblies

이호현·2021년 2월 16일
0

Algorithm

목록 보기
82/138

[문제]

Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

Notes:

  • Only lower case letters will be used (a-z). No punctuation or digits will be included.
  • Performance needs to be considered

    Input strings s1 and s2 are null terminated.

Examples

scramble('rkqodlw', 'world') ==> True
scramble('cedewaraaossoqqyt', 'codewars') ==> True
scramble('katas', 'steak') ==> False

(요약) 두 번째 문자열 각각 요소가 첫 번째 문자열에 모두 있는지 확인. 중복 불가.

[풀이]

function scramble(str1, str2) {
  const charIndexes = {};

  for(let i = 0; i < str2.length; i++) {
    if(str1.indexOf(str2[i], (charIndexes[str2[i]] + 1) || '0') === -1) {
      return false;
    }

    charIndexes[str2[i]]
      ? charIndexes[str2[i]] = str1.indexOf(str2[i], charIndexes[str2[i]] + 1)
      : charIndexes[str2[i]] = str1.indexOf(str2[i]);
  }

  return true;
}

처음에 시도했던게 반복문을 이용해서 str2의 각 요소가 str1에 없으면 falsereturn하고, 있으면 str1에서 그 문자를 replace로 치환하려고 했는데 테스트 케이스 중에 엄청 긴게 있어서 타임아웃이 나버림.

그래서 요소를 찾을 때 마다 그 index를 관리하는 객체를 하나 만들고, 처음 찾는 문자면 처음 발견한 index를 저장하고, 다음에 또 같은 문자를 찾아야되면 그 다음 index부터 검색하게 함.
끝까지 조건문을 안타면 문자가 전부 있는것이니 truereturn하게 하면 됨.

profile
평생 개발자로 살고싶습니다

0개의 댓글